Dates & MySQL

February 13th, 2006

I recently heard about someone who used to store dates in their DB, retrieve them, and then use mktime(), date() etc to then use that date in a more readable format! So here's a quick look into some of the ways to retrieve dates from MySQL and format them.

Timestamps are your Friend

The UNIX timestamp is a count of the number of seconds since 1st January 1970. The date() function in PHP can format a UNIX timestamp into a large number of user-defineable formats:

PHP:
  1. $ts = 1139851502;
  2. echo date("D d M Y",$ts)."n"; //Mon 13 Feb 2006
  3. echo date("F j, Y, g:i a",$ts)."n"; //February 13, 2006, 5:25 pm
  4. echo date("D M j G:i:s T Y",$ts)."n"; //Mon Feb 13 17:25:02 UTC 2006
  5. echo date("r",$ts)."n"; //Mon, 13 Feb 2006 17:25:02 +0000

You can get MySQL to give you a UNIX timestamp by specifying so in your query:

SELECT id,name,UNIX_TIMESTAMP(date) FROM table

This will give you a timestamp that you can then use with the date() function to format.

Let MySQL Do The Hard Work

I'm a believer that you should let MySQL do the work if possible. You can in fact get MySQL to format the date within your SELECT query, and return the date as you want it:

mysql> SELECT DATE_FORMAT(date, '%W %M %Y') FROM table;
-> 'Saturday October 1997'
mysql> SELECT DATE_FORMAT(date, '%H:%i:%s') FROM table;
-> '22:23:00'

More information on DATE_FORMAT can be found in the manual.


 Add to del.icio.us    Digg this    Technorati

Related Posts:

Entry Filed under: PHP, MySQL

3 Comments Add your own

  • 1. Joseph Scott  |  February 13th, 2006 at 6:35 pm

    Formatting dates this way probably leaves with a MySQL only solution though. Formatting the date in PHP at least gives you once less problem when trying to support multiple databases.

  • 2. Nate K  |  February 24th, 2006 at 3:11 pm

    I would agree with the above post, as well as some other issues I have ran into.

    I recently did a site that required a timeline. This timeline had MANY dates before 1970 - so therefore a different format HAD to be used.

    Though i think its good to do things on the MySQL end, I tend to do the majority of it through the programming to keep my queries and formatting separately.

  • 3. Ethan  |  May 1st, 2006 at 1:15 pm

    The UNIX Timestamp also has one other floor. It only goes to 2038. Seeing as I am dealing with programs that have to calculate 20-30 years ahead I have had to revert to datetime()

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

February 2006
M T W T F S S
« Jan   Mar »
 12345
6789101112
13141516171819
20212223242526
2728  

Most Recent Posts