Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the number of days in a month in SQL Server?

I need to determine the number of days in a month for a given date in SQL Server.

Is there a built-in function? If not, what should I use as the user-defined function?

like image 755
Even Mien Avatar asked Mar 27 '09 18:03

Even Mien


People also ask

How do I get the number of days in SQL?

Use the DATEDIFF() function to retrieve the number of days between two dates in a MySQL database. This function takes two arguments: The end date. (In our example, it's the expiration_date column.)

What is Eomonth SQL?

An optional integer expression that specifies the number of months to add to start_date. If the month_to_add argument has a value, then EOMONTH adds the specified number of months to start_date, and then returns the last day of the month for the resulting date.


2 Answers

In SQL Server 2012 you can use EOMONTH (Transact-SQL) to get the last day of the month and then you can use DAY (Transact-SQL) to get the number of days in the month.

DECLARE @ADate DATETIME  SET @ADate = GETDATE()  SELECT DAY(EOMONTH(@ADate)) AS DaysInMonth 
like image 146
Mikael Eriksson Avatar answered Oct 16 '22 18:10

Mikael Eriksson


You can use the following with the first day of the specified month:

datediff(day, @date, dateadd(month, 1, @date)) 

To make it work for every date:

datediff(day, dateadd(day, 1-day(@date), @date),               dateadd(month, 1, dateadd(day, 1-day(@date), @date))) 
like image 25
mmx Avatar answered Oct 16 '22 16:10

mmx