PHP DateTime microseconds always returns 0

前端 未结 18 2480
萌比男神i
萌比男神i 2020-12-01 02:55

this code always returns 0 in PHP 5.2.5 for microseconds:

format(\"Y-m-d\\TH:i:s.u\") . \"\\n\";
?>

18条回答
  •  鱼传尺愫
    2020-12-01 03:03

    Right, I'd like to clear this up once and for all.

    An explanation of how to display the ISO 8601 format date & time in PHP with milliseconds and microseconds...

    milliseconds or 'ms' have 4 digits after the decimal point e.g. 0.1234. microseconds or 'µs' have 7 digits after decimal. Seconds fractions/names explanation here

    PHP's date() function does not behave entirely as expected with milliseconds or microseconds as it will only except an integer, as explained in the php date docs under format character 'u'.

    Based on Lucky's comment idea (here), but with corrected PHP syntax and properly handling seconds formatting (Lucky's code added an incorrect extra '0' after the seconds)

    These also eliminate race conditions and correctly formats the seconds.

    PHP Date with milliseconds

    Working Equivalent of date('Y-m-d H:i:s').".$milliseconds";

    list($sec, $usec) = explode('.', microtime(true));
    echo date('Y-m-d H:i:s.', $sec) . $usec;
    

    Output = 2016-07-12 16:27:08.5675

    PHP Date with microseconds

    Working Equivalent of date('Y-m-d H:i:s').".$microseconds"; or date('Y-m-d H:i:s.u') if the date function behaved as expected with microseconds/microtime()/'u'

    list($usec, $sec) = explode(' ', microtime());
    echo date('Y-m-d H:i:s', $sec) . substr($usec, 1);
    

    Output = 2016-07-12 16:27:08.56752900

提交回复
热议问题