Get last day of previous month in yyyy-mm-dd format

无人久伴 提交于 2020-01-06 08:09:12

问题


How do I get the last day of the previous month in yyyy-mm-dd format?

This is what I have tried, however I don't want the seconds showing. Only YYYY-MM-DD:

SELECT DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), 0))

回答1:


Use the EOMONTH function along with FORMAT:

SELECT FORMAT(EOMONTH(CURRENT_TIMESTAMP, -1), 'yyyy-MM-dd')

The -1 in the above example means subtract 1 month from argument 1 (there is no need for DATEADD).




回答2:


Convert it into date only format

SELECT convert(date,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)),103)



回答3:


this should work

 SELECT CONVERT(VARCHAR(10),  DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)), 120)  



回答4:


Try this which is popular :

 SELECT CONVERT(VARCHAR(10),DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)),120)  

Live demo




回答5:


try this:

Select CONVERT(varchar, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)),23)



回答6:


I would use this, due to newer versions of SQL supporting it:

SELECT  CONVERT(DATE,EOMONTH(DATEADD(MM,-1,GETDATE())),103)

Code is shorter to accomplish the same task...



来源:https://stackoverflow.com/questions/57674607/get-last-day-of-previous-month-in-yyyy-mm-dd-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!