PHP DateTime microseconds always returns 0

前端 未结 18 2486
萌比男神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

    This has worked for me and is a simple three-liner:

    function udate($format='Y-m-d H:i:s.', $microtime=NULL) {
        if(NULL === $microtime) $microtime = microtime();
        list($microseconds,$unix_time) = explode(' ', $microtime);
        return date($format,$unix_time) . array_pop(explode('.',$microseconds));
    }
    

    This, by default (no params supplied) will return a string in this format for the current microsecond it was called:

    YYYY-MM-DD HH:MM:SS.UUUUUUUU

    An even simpler/faster one (albeit, with only half the precision) would be as follows:

    function udate($format='Y-m-d H:i:s.', $microtime=NULL) {
        if(NULL === $microtime) $microtime = microtime(true);
        list($unix_time,$microseconds) = explode('.', $microtime);
        return date($format,$unix_time) . $microseconds;
    }
    

    This one would print out in the following format:

    YYYY-MM-DD HH:MM:SS.UUUU

提交回复
热议问题