Search code examples
phpdatetimestrtotime

convert AMPM to datetime 24 hour


I'm trying to convert 01-31-2017 09:01 AM into 24 hour datetime ( i have AM PM in my values), but it keep giving me 1969-12-31 16:00:00

Here's what I've done:

$old_date = strtotime("01-31-2017 09:01 AM");
$new_date = date('Y-m-d H:i:s', $old_date);

Any kind of help I can get on this is greatly appreciated!


Solution

  • If you know the format of the string you better use the date_create_from_format function:

    $s = '01-31-2017 09:01 AM';
    $date = date_create_from_format('m-d-Y h:i A', $s);
    var_dump($date->format('Y-m-d H:i:s'));
    

    When you use the strtotime you let the php parse the string, and it might lead to a result you are not looking for (for example - 01-02-2017 - is it jan 2nd or feb 1st?).