A Short Note: MySQL Date Formats

Wednesday, February 18, 2009

Like PHP, mySQL 5 uses a form of timestamps, in its native form, and it's not compatible with the PHP timestamp. MySQL has three time/date types: DATE, TIME, and DATETIME. MySQL also has a special date field named TIMESTAMP, which works just like DATETIME but automatically updates to the current timestamp with every insert and update and has a different internal storage mechanism.

There are some ways of representing data in your queries for these types, but it's much easier to use string in it. For example, you can use 2008-09-26 as a date, 13:23:56 as time, and 2008-09-26 13:23:56 as date and time. You can use this code to convert a PHP timestamp in $timestamp into a form suitable for mySQL:

 date('Y-m-d H:i:s', $timestamp);


Although you can store PHP/Unix timestamps as INT(100, it really helps to use the native mySQL formats you wil be able to use the data independently of PHP. To get PHP timestamp from a SELET statement, use the SQL UNIX_TIMESTAMP function, like this example:
SELECT UNIX_TIMESTAMP(date_field) FROM table;


There are a lot of useful date function in mySQL5, such as DATE_FORMAT and DATE_ADD. Check their website for a complete list.

Hope it helps.

0 comments: