I need to find the last day of a month in the following format:
\"2013-05-31 00:00:00:000\"
Anybody please help out.
declare @date datetime;
set @date = getdate(); -- or some date
select dateadd(month,1+datediff(month,0,@date),-1);
SQL Server 2012 introduces the eomonth function:
select eomonth('2013-05-31 00:00:00:000')
-->
2013-05-31
TO FIND 1ST and Last day of the Previous, Current and Next Month in Oracle SQL
-----------------------------------------------------------------------------
SELECT
SYSDATE,
LAST_DAY(ADD_MONTHS(SYSDATE,-2))+1 FDPM,
LAST_DAY(ADD_MONTHS(SYSDATE,-1)) LDPM,
LAST_DAY(ADD_MONTHS(SYSDATE,-1))+1 FDCM,
LAST_DAY(SYSDATE)LDCM,
LAST_DAY(SYSDATE)+1 FDNM,
LAST_DAY(LAST_DAY(SYSDATE)+1) LDNM
FROM DUAL
I know this question was for SQL Server 2005, but I thought I'd mention- as of SQL 2012, there now is an EOMONTH()
function that gets the last day of the month. To get it in the format specified by the original asker you'd have to cast to a datetime
.
SELECT CAST(eomonth(GETDATE()) AS datetime)
Just a different version of adding a month and subtracting a day for creating reports:
ex: StartofMonth is '2019-10-01'
dateadd(day,-1,dateadd(month,1,StartofMonth))
EndOfMonth will become '2019-10-31'
Try this one -
CREATE FUNCTION [dbo].[udf_GetLastDayOfMonth]
(
@Date DATETIME
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @Date) + 1, 0))
END
Query:
DECLARE @date DATETIME
SELECT @date = '2013-05-31 15:04:10.027'
SELECT DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @date) + 1, 0))
Output:
-----------------------
2013-05-31 00:00:00.000