How to convert ISO8601 to Date format in php

33,221

Solution 1

try this

$date = '2014-03-13T09:05:50.240Z';

$fixed = date('Y-m-d', strtotime($date));

The complete date function documentation can be found here: http://php.net/manual/en/function.date.php

The PHP function "strtotime" does nothing else then converting your timestring into an unix timestamp.

Hope I could help :)

P.s.: Just in case strtotime will return 0 try using this:

$date = '2014-03-13T09:05:50.240Z';

$fixed = date('Y-m-d', strtotime(substr($date,0,10)));

Solution 2

Since PHP 5.2.0 you can do it using OOP and DateTime() as well (of course if you prefer OOP):

$now = new DateTime("2014-03-13T09:05:50.240Z");
echo $now->format('Y-m-d');    // MySQL datetime format

Solution 3

There is no reason to use the inefficient time functions. The most efficient way is to simply extract the first 10 characters:

substr($date,0,10)

People, that are really coding for year ≥10000, can use:

substr($date,0,strpos($date,"T"))

Solution 4

Simply convert datetime description into a Unix timestamp using with strtotime and then five format using Date Formats

Try it will surely work for you.

$date = '2014-03-13T09:05:50.240Z';

$fixed = date('Y-m-d', strtotime($date));
Share:
33,221
Neel
Author by

Neel

Previously know as @blackops_programmer. I know, it was a pretty lame Display name.

Updated on January 25, 2022

Comments

  • Neel
    Neel over 2 years

    How to convert this (in ISO8601 format): 2014-03-13T09:05:50.240Z

    To this (in MySQL DATE format): 2014-03-13

    in php?