Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of days in a month in SQL Server

Tags:

sql

sql-server

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?

like image 708
CodeMachine Avatar asked Aug 09 '18 12:08

CodeMachine


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.

How do I convert days to months in SQL?

I have the following query SELECT TRUNC(MONTHS_BETWEEN(SYSDATE,DOB)/12) YEAR, TRUNC(MOD(MONTHS_BETWEEN(SYSDATE,DOB),12)) MONTH, TRUNC(SYSDATE-ADD_MONTHS(DOB,TRUNC(MONTHS_BETWEEN(SYSDATE,DOB)/12)*12+TRUNC(MOD(MONTHS_BETWEEN(SYSDATE,DOB),12)))) DAY FROM table_name; which gives following results.

How can get month and day from date in SQL?

If you use SQL Server, you can use the DAY() or DATEPART() function instead to extract the day of the month from a date. Besides providing the EXTRACT() function, MySQL supports the DAY() function to return the day of the month from a date.


5 Answers

You can use:

select day(eomonth ('2018-02-01')) as NoOfDays

and the result will be:

NoOfDays
-----------
28
like image 130
AswinRajaram Avatar answered Oct 11 '22 00:10

AswinRajaram


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)))
like image 42
Gordon Linoff Avatar answered Oct 10 '22 23:10

Gordon Linoff


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.

like image 31
Andrew Avatar answered Oct 10 '22 23:10

Andrew


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))
like image 4
t-clausen.dk Avatar answered Oct 11 '22 00:10

t-clausen.dk


try using

SELECT day(eomonth(yourdate))
like image 3
Chanukya Avatar answered Oct 10 '22 23:10

Chanukya