Is there a way to get the number of days in a month in SQL Server, if we input the month number or month name, or even a date?
Asked
Active
Viewed 1.2k times
7
-
Possible duplicate of [How to determine the number of days in a month in SQL Server?](https://stackoverflow.com/questions/691022/how-to-determine-the-number-of-days-in-a-month-in-sql-server) – sniperd Aug 09 '18 at 13:14
6 Answers
12
You can use:
select day(eomonth ('2018-02-01')) as NoOfDays
and the result will be:
NoOfDays
-----------
28

AswinRajaram
- 1,519
- 7
- 18
10
If you have a date, then simply do:
select day(eomonth(date))
If you have a month number, then:
select day(eomonth(datefromparts(2020, month_number, 1)))

Gordon Linoff
- 1,242,037
- 58
- 646
- 786
-
@CodeMachine . . . You are the OP and can accept whichever answer you like. However, I'm curious why you unaccepted this answer for an equivalent answer posted several minutes later. – Gordon Linoff Aug 10 '18 at 10:27
5
If you have a date and are on 2012 or later :
SELECT day(eomonth(yourdate))
Month name / number is automatically prone to an error when dealing with February - do you consider it 28 or 29, which year are you referring to when making that calculation etc.

Andrew
- 26,629
- 5
- 63
- 86
4
In case you are using sql-server 2008 or earlier:
Date as input
DECLARE @date DATETIME = getdate()
SELECT day(dateadd(m, datediff(m, -1, @date), -1))
Month and year as input
DECLARE @year INT = 2018
DECLARE @month INT = 2
SELECT day(dateadd(m, @month + datediff(m, 0, cast(@year as char(4))), -1))

t-clausen.dk
- 43,517
- 12
- 59
- 92
2
for pre 2012 where eomonth()
is not available
if you have a date
select day(dateadd(month, datediff(month, 0, @date) + 1, -1))
if you have the year & month
declare @year int = 2018,
@month int = 8
select dateadd(month, @month, dateadd(year, @year - 1900, -1))

Squirrel
- 23,507
- 4
- 34
- 32