Archive for the ‘Tips’ Category

Dealing with MySQL Date

Friday, October 2nd, 2009

Assuming you are using MySQL as your database a data type of ‘date’ is stored as ‘YYYY-MM-DD’. In PHP we can represent the MySQL date data type by using the date() function like so.


echo date('Y-m-d');
//Result: 2010-10-02

One of the stumbling blocks I ran into was having to convert a stored date in a MySQL database to a user friendly format. There is a simple solution to this which is the strtotime() function.


$db_date = '2010-10-02';
echo date('F j, Y', strtotime($db_date));
//Result: October 2, 2010

When converting dates for entry into a database, you will likely collect the year, month, and date from a form as separate variables. If this is the case you can easily convert the variables into a MySQL ready date by using the mktime() function.


$year = 2010;
$month = 10;
$day = 2; //notice the 2 is not padded with a zero
$db_date = date('Y-m-d', mktime(0, 0, 0, $month, $day, $year));
echo $db_date;
//Result: 2010-10-02

So there you have it. Passing dates between a MySQL database and your application should now be a snap. If you aren’t familiar with PHP’s date() function, go to the page and bookmark it now because I find myself constantly going back there.

Before I leave you alone, I might as well give you the PHP representation for a MySQL ‘datetime’ data type.


echo date('Y-m-d H:i:s');
//Result: 2010-10-02 00:32:15