Tony
Tony

Reputation: 287

PHP String to DateTime with AM/PM

It is posible to convert my string with this format "A H:i m/d/y" to a DateTime in php?

Example string: AM 05:28 07/08/13

This don't work

$date = DateTime::createFromFormat('A H:i m/d/y', 'AM 05:28 07/08/13');

This works:

$date = DateTime::createFromFormat('H:i m/d/y', '05:28 07/08/13');

$date = DateTime::createFromFormat('H:i m/d/y A', '05:28 07/08/13 AM');

Ugly work around:

$myDate = 'AM 05:28 07/08/13';
$myDate = substr($myDate, 3, strlen($myDate)-3)." ".substr($myDate, 0, 2);

$date = DateTime::createFromFormat('H:i m/d/y A', $myDate);

Upvotes: 10

Views: 3597

Answers (1)

Dmitriy.Net
Dmitriy.Net

Reputation: 1500

This is a php bug. Try to use next function:

function createFromFormat($format, $time)
{       
    $is_pm  = (stripos($time, 'PM') !== false);
    $time   = str_replace(array('AM', 'PM'), '', $time);
    $format = str_replace('A', '', $format);

    $date   = DateTime::createFromFormat(trim($format), trim($time));

    if ($is_pm)
    {
        $date->modify('+12 hours');
    }

    return $date;
}


$date = createFromFormat('H:i m/d/y A', '05:28 07/08/13 AM');
var_dump($date->format('d.m.Y H:i')); //  string(16) "08.07.2013 05:28" 

$date = createFromFormat('H:i m/d/y A', '05:28 07/08/13 PM');
var_dump($date->format('d.m.Y H:i')); //  string(16) "08.07.2013 17:28" 

Upvotes: 2

Related Questions