Time and Date Functions in MySQL

Working with dates and times in MySQL is straightforward and there are several MySQL functions to do the calculations for you. Some of the most common requirements are to calculate the current date and time, and this can be done with the CURRENT_DATE() and NOW() functions like this:

mysql> SELECT CURRENT_DATE();
2011-03-01
mysql> SELECT NOW();
2011-03-01 17:30:00

Sometimes you might want to extract some of the date or time information from a value held in a field. The year(), month(), hour(), minute() and second() functions will extract the pertinent part of the date value as the following examples demonstrate:

mysql> SELECT YEAR(‘2011-03-01’);
2011
mysql> SELECT MONTH(‘2011-03-01’);
03
mysql> SELECT HOUR(NOW());
17

You can use four different functions to extract day information from the date depending on how you need the result. This example shows these functions:

mysql> SELECT DAYOFMONTH(NOW());
2
mysql> SELECT DAYNAME(NOW());
Tuesday
mysql> SELECT DAYOFWEEK(NOW());
3
mysql> SELECT DAYOFYEAR(NOW());
61

Now that you know how to extract date information, you can use that in calculations. To work out the age of a person, you can subtract their birthday from the current date.

SELECT YEAR(CURRENT_DATE()) – YEAR(birthday);

This will work as long as the person has already celebrated their birthday. If the birthday is later in the year then it will return an incorrect value. The only way around this is to test on the month and day portion of the birthday. This code segment uses the date_format() function to calculate the age if the birthday has already passed this year:

SELECT YEAR(CURRENT_DATE()) - YEAR(birthday) -
(date_format(CURRENT_DATE(), '%m-%y')<) AS age;

Get notified of new posts:


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *