Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP String to DateTime with AM/PM

Tags:

php

datetime

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);
like image 237
Tony Avatar asked May 08 '14 21:05

Tony


People also ask

How can change time in 24 hour format in PHP?

php //current Date, i.e. 2013-08-01 echo date("Y-m-d"); //current Time in 12 hour format, i.e. 08:50:55pm echo date("h:i:sa"); //current Time in 24 hour format, i.e. 18:00:23 echo date("H:i:s"); //current Month, i.e. 08 echo date("m"); //current Month name, i.e. Aug echo date("M"); ?>


1 Answers

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" 
like image 113
Dmitriy.Net Avatar answered Sep 24 '22 08:09

Dmitriy.Net