Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of days of a month given the particular month and year?

Tags:

mysql

I am new to sql and programming so please bear with me. Is there a function in mysql that gets the number of days in a month? Example if the month is February and the year 2012 it should return 29. Thanks in advance.

like image 438
NinjaBoy Avatar asked Feb 23 '12 02:02

NinjaBoy


People also ask

How do you calculate the number of days in a month between two dates?

This might be what you are looking for. Show activity on this post. Go to the first day of the next month, and subtract one day. That gives you the total number of days for the current month.


1 Answers

There's no direct "last day of month", but you can fake it by doing a day(last_day())

mysql> select last_day('2012-02-22'), day(last_day('2012-02-22'));
+------------------------+-----------------------------+
| last_day('2012-02-22') | day(last_day('2012-02-22')) |
+------------------------+-----------------------------+
| 2012-02-29             |                          29 | 
+------------------------+-----------------------------+
1 row in set (0.00 sec)

last_day() returns the full date of the last day in in the year/month of a specified date, so you then simply use day() to extract the day of that last_day.

MySQL's date/time functions documentation is here: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

like image 66
Marc B Avatar answered Nov 14 '22 23:11

Marc B