Wednesday, November 16, 2022

How to Get the Last Day of the Month in T-SQL

We’ll use the function EOMONTH() to find the last day of the month.

DECLARE @fromdate DATETIME, @EOMMonthdate DATETIME

SET @fromdate = '11/01/2022'

SET @EOMMonthdate = EOMONTH(@fromdate,0) -- for current month

SELECT @EOMMonthdate as lastdayOfthemonth
  

If you want to return the last day of the second, third, etc. month from a given date, use EOMONTH()’s optional second argument: the number of months to add. Look at the examples for last day of next month or last day of the previous month.

DECLARE @fromdate DATETIME, @EOMMonthdate DATETIME

SET @fromdate = '11/01/2022'

SET @EOMMonthdate = EOMONTH(@fromdate,1) -- for next month last day

SELECT @EOMMonthdate as nextMonthLastDayOfthemonth

SET @EOMMonthdate = EOMONTH(@fromdate,-1) -- for previous month last day

SELECT @EOMMonthdate as previousMonthLastday
  

Hope this helps!!

No comments:

Post a Comment