Archive

Posts Tagged ‘end of month’

SQL Server – "Denali" – End of Month using EOMONTH()

26.07.2011 3 comments

SQL Server Denali CTP3 introduces a new date/time function EOMONTH(). EOMONTH() returns the last day of the month for the given date. It also accepts an optional argument which is an integer expression specifying number of months to add/remove from specified date.

Syntax:

       EOMONTH( start_date [, months_to_add] )

It’s similar to Excel’s EOMONTH() function to calculate last day of the month.

It can be used as below:

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

       AS 'Last day of Month', — Earlier Versions

       EOMONTH(GETDATE())

       AS 'Last day of Month',

       DATEADD(s, 1, DATEADD(day, 1, EOMONTH(GETDATE())))

       AS 'Last day of Month'

       — Time part 23:59:59

Result Set:

Last day of Month       Last day of Month       Last day of Month

———————– ———————– ———————–

2011-07-31 23:59:59.000 2011-07-31 00:00:00.000 2011-07-31 23:59:59.000

 

(1 row(s) affected)

You can use DATEADD() and EOMONTH() to calculate first day of the month as follows:

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)

       AS 'First day of Month', — Earlier Versions

       DATEADD(day, 1, EOMONTH(GETDATE(), 1))

       AS 'First day of Month'

Result Set:

First day of Month      First day of Month

———————– ———————–

2011-07-01 00:00:00.000 2011-07-01 00:00:00.000

 

(1 row(s) affected)

Hope This Helps!

Vishal