PHP/MySQL datetime formatting bypassing UNIX_TIMESTAMP

Tags:

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!

Related posts:

  1. [MySQL] Setting date data type default value NULL instead of 0000-00-00
  2. [MySQL] Enabling MySQL Query Cache to Speed Up Query Performance
  3. Backup your MySQL databases automatically with cron job