Search code examples
phpdatestrtotimedate-formatting

PHP date conversion using strtotime


I have a date in the ymd format. Example for 2014-05-28 I actually have: 140528.

I would like to convert it to the date(c") format. Example: 2014-05-28T00:00:00-04:00

I cannot use DateTime::createFromFormat because of my php version. So instead I tried strtotime, but with no success:

$d[14]="140528";
$deliveryDate = date('ymd', $d[14]);
$d[14] = date("c", strtotime($deliveryDate));

strtotime is not recognizing the original date format as it returns me the 1969 date.


Solution

  • Break it up into parts and then form a valid date out of those parts. Then strtotime() will work.

    $badDate = "140528";
    $date = sprintf("20%s-%s-%s",
        substr($badDate, 0, 2),
        substr($badDate, 2, 2),
        substr($badDate, 4, 2)
    );
    
    echo date("c", strtotime($date));
    

    Demo