如何在 SQL Server 中获取上个月的第一天和最后一天(带时间戳) [英] How to get first and last day of previous month (with timestamp) in SQL Server

查看:45
本文介绍了如何在 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

这篇关于如何在 SQL Server 中获取上个月的第一天和最后一天(带时间戳)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆