Convert from MySQL datetime to another format with PHP

Solution 1:

If you're looking for a way to normalize a date into MySQL format, use the following

$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );

The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.

The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.

(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)

Solution 2:

To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)):

// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM

Refer to the PHP date formatting options to adjust the format.

Solution 3:

If you are using PHP 5, you can also try

$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");

Solution 4:

$valid_date = date( 'm/d/y g:i A', strtotime($date));

Reference: http://php.net/manual/en/function.date.php

Solution 5:

Finally the right solution for PHP 5.3 and above: (added optional Timezone to the Example like mentioned in the comments)

without time zone:

$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);
echo $date->format('m/d/y h:i a');

with time zone:

$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
echo $date->format('m/d/y h:i a');