PHP/MySQL datetime formatting bypassing UNIX_TIMESTAMP

by Ali on April 15th, 2010

PHP/MySQL datetime formatting bypassing UNIX_TIMESTAMP

Formatting MySQL date to something useful has been a pain for PHP developers for a long time.

Usually you would make your query return the datetime using UNIX_TTIMESTAMP and then using PHP date function, format it to your heart’s content like this:

  echo date("F jS, Y h:i:s A", $row->date);

But this method has a downside, you can’t use the * and have to put all the fields in the query to use UNIX_TIMESTAMP for datetime field and have it returned as timestamp.

A better way of doing this is, especially in the scenario when you have to use * in the query, by using PHP5 DateTime Object. This way you can avoid UNIX_TIMESTAMP.

$myDate = new DateTime($row->date); 
$date = $oDate->format("F jS, Y h:i:s A ");

Hope it helps.

Cheers!

No related posts.

From → PHP Development

No comments yet

Leave a Reply

You must be logged in to post a comment.