DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
有人可以解释一下吗。
这将为您提供给定日期的第一个月的第一天
内部选择
select DATEDIFF(MONTH, 0, GETDATE())
将给出从 1900-01-01 开始的月份数
这里是 1350
这将添加到 1900-01-01 ,但只有几个月
select DATEADD(MONTH,1350,0)
将给 2012-07-01 00:00:00.000
这是当月的开始。
我认为这是查找任何给定日期的月初的最有效方法。
DateDiff 函数返回多少秒、多少个月、多少年——您在第一个日期(此处为 0)和第二个日期(此处为当前日期)之间指定的任何间隔。
DATEDIFF(MONTH, 0, '2-14-2015') --returns month. 0 is for 1/1/1900, and getdate is the current date
--(i used a set date bc dates will change as this post gets older).
result: 1381
在我的工作中,我使用了 2-14-2015 的日期,它给了我自 1900 年 1 月 1 日以来的 1381 个月。我像这样将 1381 放入 dateadd 函数中......
select Dateadd(MONTH, 1381, 0)
result: 2015-02-01 00:00:00.000
基本上,它获取最内层公式的日期中指定的任何月份的第一天。
我必须弄清楚的代码更进一步,并从该结果中减去 1 秒,以便在 11:59:59 获得该月的最后一天,就像这样......
select DATEADD(s, -1, '2015-02-01 00:00:00.000')
公式全部放在一起看起来像这样:
DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())+1,0))
希望这可以帮助某人。:)
The DATEDIFF will give you date diff in month from January 1 1900 to current date
AND
The DATEADD will add (DATEDIFF) results months to your last parameter of DATEADD
It's getting the start of the current month. It counts the number of months since January 1900, and adds on them to January 1 1900 to get the start of the current month
DATEADD 函数将时间间隔添加到您指定的日期。例如,如果 SalesOrderHeader 表中的所有订单的到期日期滑动了 3 天,您可以使用以下语句获取新日期:
USE AdventureWorks;
GO
SELECT DATEADD(day, 3, DueDate)
FROM Sales.SalesOrderHeader;
GO
DATEDIFF 函数计算您指定的两个日期的第二个和第一个日期之间的时间段。换句话说,它找到两个日期之间的间隔。结果是一个有符号整数值,等于日期部分中的 date2 - date1。以下查询使用 2001 年 11 月 30 日这一日期,并找出 DueDate 与该日期之间经过的天数:
USE AdventureWorks;
GO
SELECT DATEDIFF(day, DueDate, 'Nov 30 2001')
FROM Sales.SalesOrderHeader;
GO
SELECT DATEDIFF(year, '20051220', '20060101')
SELECT DATEDIFF(month, '20051220', '20060101')
SELECT DATEDIFF(day, '20051220', '20060101')