码迷,mamicode.com
首页 > 其他好文 > 详细

日期的最后一天和第一天

时间:2016-08-12 20:07:40      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

一,月份的最后一天

Returns the last day of the month that contains the specified date, with an optional offset.

EOMONTH ( start_date [, month_to_add ] )

1,对于start_date 有两种输入方式,能够转换为Date的字符串类型 和 date 数据类型。

declare @date date
set @date=getdate()

select EOMONTH(@date)
select EOMONTH(2016-08-06),EOMONTH(20160806)

2,month_to_add 是int 类型,能够为正整数,负整数和0,默认值是0,如果省略,那么使用默认值0。

declare @date date
set @date=getdate()

select EOMONTH(@date) as CurrentMonth_EndDay,
    EOMONTH(@date,1) as NextMonth_EndDay,
    EOMONTH(@date,-1) as LastMonth_EndDay

3,季度的最后一天

使用EOMONTH获取季度的最后一天,只需要指定季度最后一个月的任意一天即可,季度的最后一个月份是固定的:3*quarter_num,可能值是:3,6,9,12.

declare @date date
set @date=getdate()

select DATEPART(quarter,@date) as quarter_num

select EOMONTH(DATEFROMPARTS(year(@date),DATEPART(quarter,@date)*3,1))

二,月份的第一天
Returns a date value for the specified year, month, and day.

DATEFROMPARTS ( year, month, day )

使用DateFromParts 函数,能够从三个正整数(year,month,day)中获取date 类型。

1,只需要将day 参数设置1,就能获取月份的第一天。

declare @date date
set @date=getdate()

select DATEFROMPARTS(year(@date),month(@date),1) 

2,获取季度的第一天

首先使用DATEPART 函数获取当前日期的季度,可能值为:1,2,3,4.

declare @date date
set @date=getdate()

select DATEPART(quarter,@date) as quarter_num

季度的第一天是季度一个月的第一天,那么季度第一个月份 符合公式: (quarter_num-1)*3+1,等价于 quarter_num*3-2

declare @date date
set @date=getdate()

select DATEFROMPARTS(year(@date),DATEPART(quarter,@date)*3-2,1) 

 

参考doc:

DATEPART (Transact-SQL)

DATEFROMPARTS (Transact-SQL)

EOMONTH (Transact-SQL)

日期的最后一天和第一天

标签:

原文地址:http://www.cnblogs.com/ljhdo/p/5763143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!