问题
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