Search code examples
phpdate-formattingiso8601

strtotime drops microseconds from ISO8601 format, is there an alternative function that doesn't?


When I do:

echo(strtotime('2020-06-16T08:08:18.339Z'));

strtotime gives me:

1592294898

Is there a function to convert date/time in ISO8601 format without dropping microseconds? (To a fractional number of seconds, similar to the one returned by microtime(true) function.)

PS. I'm using PHP 7.4


Solution

  • As always with dates in PHP, DateTime to the rescue

    $str = '2020-06-16T08:08:18.339Z';
    
    $dt = new DateTime($str); // or DateTime::createFromFormat('Y-m-d\TH:i:s.uO', $str);
    
    echo (float) $dt->format('U.u');
    

    Demo ~ https://3v4l.org/ee9MZ


    You could also use the DATE_RFC3339_EXTENDED constant in createFromFormat if you're only interested in milliseconds but your question says "microseconds".