The Blueprint
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.
Search The Blog
Code & Projects
Categories
Archives
- October 2009
- September 2009
- August 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- April 2008
- March 2008
- February 2008
- July 2007