MySQL date and time functions, Part 2 - Page 2April 15, 2003 Date formatsThe DATE_FORMAT function is a powerful function that allows you to return a specified date in a number of different ways. For example, those who use American time (MM-DD-YYYY, as you can see at the beginning of this article) instead of the standard International time, this function provides a painless way to convert. Below is a list of format specifiers:
mysql> SELECT DATE_FORMAT('2003-07-14','%b %d,%Y');
+--------------------------------------+
| DATE_FORMAT('2003-07-14','%b %d,%Y') |
+--------------------------------------+
| Jul 14,2003 |
+--------------------------------------+
A subset of this function is the TIME_FORMAT() function, which is identical, but allows you to use those formats to do with time.The last function we are going to look at specifically will be meaningful to those of you familiar with the concept of Unix time. Unix time is the time in seconds since midnight 1 January 1970, and is used by many applications. The UNIX_TIMESTAMP() function returns the Unix time of the current time When called without a parameter, or converts a specified date if one is supplied.
mysql> SELECT UNIX_TIMESTAMP();
+------------------+
| UNIX_TIMESTAMP() |
+------------------+
| 1050267998 |
+------------------+
mysql> SELECT UNIX_TIMESTAMP('2003-07-14');
+------------------------------+
| UNIX_TIMESTAMP('2003-07-14') |
+------------------------------+
| 1058133600 |
+------------------------------+
Looking at the possibilities available with this function, along with the date and time calculations we've looked at already, you can see there's not always that much need to do this inside the application!
Below is a reference for the MySQL date and time functions. Once you have mastered what we've covered so far, none of the other functions will present anything tricky, but you should give the list a read through - you never know when you'll need them. |