Database Reference
In-Depth Information
Decomposing dates or times using formatting functions
The DATE_FORMAT() and TIME_FORMAT() functions reformat date and time values. By
specifying appropriate format strings, you can extract individual parts of temporal val‐
ues:
mysql> SELECT dt,
-> DATE_FORMAT(dt,'%Y') AS year,
-> DATE_FORMAT(dt,'%d') AS day,
-> TIME_FORMAT(dt,'%H') AS hour,
-> TIME_FORMAT(dt,'%s') AS second
-> FROM datetime_val;
+---------------------+------+------+------+--------+
| dt | year | day | hour | second |
+---------------------+------+------+------+--------+
| 1970-01-01 00:00:00 | 1970 | 01 | 00 | 00 |
| 1999-12-31 09:00:00 | 1999 | 31 | 09 | 00 |
| 2000-06-04 15:45:30 | 2000 | 04 | 15 | 30 |
| 2017-03-16 12:30:15 | 2017 | 16 | 12 | 15 |
+---------------------+------+------+------+--------+
Formatting functions are advantageous when you want to extract more than one part
of a value, or display extracted values in a format different from the default. For example,
to extract the entire date or time from DATETIME values, do this:
mysql> SELECT dt,
-> DATE_FORMAT(dt,'%Y-%m-%d') AS 'date part',
-> TIME_FORMAT(dt,'%T') AS 'time part'
-> FROM datetime_val;
+---------------------+------------+-----------+
| dt | date part | time part |
+---------------------+------------+-----------+
| 1970-01-01 00:00:00 | 1970-01-01 | 00:00:00 |
| 1999-12-31 09:00:00 | 1999-12-31 | 09:00:00 |
| 2000-06-04 15:45:30 | 2000-06-04 | 15:45:30 |
| 2017-03-16 12:30:15 | 2017-03-16 | 12:30:15 |
+---------------------+------------+-----------+
To present a date in other than CCYY-MM-DD format or a time without the seconds part,
do this:
mysql> SELECT dt,
-> DATE_FORMAT(dt,'%M %e, %Y') AS 'descriptive date',
-> TIME_FORMAT(dt,'%H:%i') AS 'hours/minutes'
-> FROM datetime_val;
+---------------------+-------------------+---------------+
| dt | descriptive date | hours/minutes |
+---------------------+-------------------+---------------+
| 1970-01-01 00:00:00 | January 1, 1970 | 00:00 |
| 1999-12-31 09:00:00 | December 31, 1999 | 09:00 |
| 2000-06-04 15:45:30 | June 4, 2000 | 15:45 |
| 2017-03-16 12:30:15 | March 16, 2017 | 12:30 |
+---------------------+-------------------+---------------+
Search WWH ::




Custom Search