如何在 SQL Server 中获取上个月的第一天和最后一天(带时间戳)
我找不到给出上个月第一天和最后一天带时间戳的解决方案.希望这对其他人有帮助.如果已经有针对此问题的解决方案,我深表歉意.
I could not find the solution which gives first and last day of previous month with timestamp. Hope this helps others. If there is already a solution for this problem I apologize.
这是解决方案.
SELECT DATEADD(month, DATEDIFF(month, -1, getdate()) - 2, 0) as FirtDayPreviousMonthWithTimeStamp,
DATEADD(ss, -1, DATEADD(month, DATEDIFF(month, 0, getdate()), 0)) as LastDayPreviousMonthWithTimeStamp
如果 currentdate = '2012-7-31'
结果:2012-06-01 00:00:00.000 2012-06-30 23:59:59.000
如果 currentdate = '2012-1-1'
结果:2011-12-01 00:00:00.000 2011-12-31 23:59:59.000
推荐答案
select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) --First day of previous month
select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) --Last Day of previous month
相关文章