Ryan

PHP DateTime object and MySQL

April 27, 2009 by Ryan in Code, PHP


PHP 5.2 brought us native use of a DateTime object for handling dates and times instead of using procedural date(), time() and strtotime() type functions. Among other things, this really helps us move away from thinking of dates and times in seconds (via a unix timestamp) and as such, having to save an integer in a database and/or using arithmetic (# of seconds X 60 = minutes, etc..) to manipulate dates.

So now that we can think of dates and times as a true date (e.g. 2009/04/27) all the way from PHP to MySQL, using a true date/time column type, it really speeds thing up. However, in the native DateTime class constants there is not a MySQL format for inserting the date object directly into a database. I realized that all I needed to do was create my own constant that aligns with the prebuilt ones.

Here is the only code you need

define('DATE_MYSQL', "Y/m/d H:i:s");

Here it is in context.

define('DATE_MYSQL', "Y/m/d H:i:s");

$dateTime = new DateTime("now");
echo $dateTime->format(DATE_MYSQL);

You’ll notice I use the same format as the other date constants like DATE_RSS to be consistent. Also note that with this same code you can set up any type of format that you can use on your site or in your code.

0 Comments
Comment Preview

September 18, 2008 by
Leave a comment

Name: *

Email: * (will never be displayed)

Website:

Comments: *

* - Required