MySQL Date and Time Types
There are a number of useful date and time functions in MySQL. I've seen too
many applications performing date calculations at the code level when the same
can be done using built-in MySQL functions. Before we launch into the functions,
however, let's refresh our memory and look at which date and time types are
available to MySQL.
DATETIME YYYY-MM-DD HH:MM:SS
DATE YYYY-MM-DD
TIMESTAMP YYYYMMDDHHSSMM
TIME HH:MM:SS
YEAR YYYY
The TIMESTAMP column stores the full 14 characters, but you can display it in
different ways. If you define the column as TIMESTAMP(2), for example, only the
two-digit year will be displayed, but the full value is stored. If you later
decide to display the full value, you can change the table definition, and the
full value will appear.
Below is a list of various ways to define a TIMESTAMP, and the resultant
display.
TIMESTAMP(14) YYYYMMDDHHMMSS
TIMESTAMP(12) YYMMDDHHMMSS
TIMESTAMP(10) YYMMDDHHMM
TIMESTAMP(8) YYYYMMDD
TIMESTAMP(6) YYMMDD
TIMESTAMP(4) YYMM
TIMESTAMP(2) YY
MySQL is quite lenient in how it reads date formats. Although it is wise to use
the convention, you can use any other punctuation character you like. For
example, if you created the following table:
CREATE TABLE time_table(dt DATETIME);
Instead of inserting a record using the convention, as follows:
INSERT INTO time_table(dt) VALUES('2011-11-07 11:22:12');
you could use '=' and '+' signs, as follows:
INSERT INTO time_table(dt) VALUES('2011=11=07 11+22+12')
But although I'm sure they exist, I haven't come across a good reason to use
this, so I suggest you keep to the conventions unless absolutely necessary.
Simple Date Calculations
Date calculations are relatively easy. The first function we're going to look at
is the YEAR() function, which returns a year from a given date.
For example:
mysql> SELECT YEAR('2011-11-07');
We can perform simple arithmetic on a date using the '+' and '-' operators.
For example, to find out which year is five years ahead of a given date, you can
use:
mysql> SELECT YEAR('2011-11-07')+5;
And to find out which year was five years in the past:
mysql> SELECT YEAR('2011-11-07')-5;
Of course you don't have to hard-code the date. MySQL is quite capable of
telling the date and time, using the NOW() function:
mysql> SELECT NOW();
Or just the date with the CURRENT_DATE() function:
mysql> SELECT CURRENT_DATE();