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?
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.
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.
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.
You can use:
select day(eomonth ('2018-02-01')) as NoOfDays
and the result will be:
NoOfDays
-----------
28
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)))
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.
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))
try using
SELECT day(eomonth(yourdate))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With