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
Calculate the last date of the month is quite simple calculation -
Find the total months count till today's date using DATEDIFF(..,..,..) function -
Select DATEDIFF(MM,0,GETDATE())
Output - 1374, If getdate() output is "2014-07-23 19:33:46.850"
Increment by 1 into total months count -
Select DATEDIFF(MM,0,GETDATE())+1
Output - 1375, If getdate() output is "2014-07-23 19:33:46.850"
Get the first date of next month -
Select DATEADD(MM,DATEDIFF(MM,0,GETDATE())+1,0)
Output - '2014-08-01 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"
Subtract by -1 into the first date of next month, which will return last date of the current month -
Select DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,0,GETDATE())+1,0))
Output - '2014-07-31 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"
In the same manner of calculation we can achieve the -
1. Last date of next month
2. Last date of the previous month
and so on...
Try this one -
Query:
Output:
To check run:
SQL Server 2012 introduces the
eomonth
function:Calculate the last date of the month is quite simple calculation -
Output - 1374, If getdate() output is "2014-07-23 19:33:46.850"
Output - 1375, If getdate() output is "2014-07-23 19:33:46.850"
Output - '2014-08-01 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"
Output - '2014-07-31 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"
In the same manner of calculation we can achieve the - 1. Last date of next month 2. Last date of the previous month and so on...
I hope this article will help.