I strongly believe strtotime()
should be avoided when there is a format available.
$from_format = 'Y-m-d H:i:s';
$to_format = 'd M, Y h:i:s A';
$date = '2016-11-11 14:26:03';
echo DateTime::createFromFormat($from_format, $date)->format($to_format);
Outputs:
11 Nov, 2016 02:26:03 PM
Why your code fails I cannot say for certain, it works fine here but you can diagnose a little. I'm assuming in your case its because strtotime()
fails converting, returning -62169984000
which is actually 0000-00-00 00:00:00
but due to a second, minute, day and a month that is not allowed to be 0
, calculations occur resulting in 0000-00-00 00:00:00
minus 1 day and 1 month, etc being 30 Nov -0001 12:00:00
so it would appear your $obj->suspend_datetime
does not contain the correct data.
I've written 2 small functions to share that would make this whole ordeal easier to handle:
function strtodatetime($date, $format = 'Y-m-d H:i:s'){
return ($d = DateTime::createFromFormat($format, $date)) && $d->format($format) == $date ? $d : false;
}
function strtounixtime($date, $format = 'Y-m-d H:i:s'){
return ($d = DateTime::createFromFormat($format, $date)) && $d->format($format) == $date ? $d->getTimestamp() : 0;
}
echo ($dt = strtodatetime($date)) ? $dt->format($to_format) : 'invalid format';
echo date('d M, Y h:i:s A', strtounixtime($obj->approve_datetime));
In your scenario, using strtounixtime()
(a better strtotime()
) it would translate back to the unix epoch if it fails.