PHP DateTime microseconds always returns 0

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

    Some answers make use of several timestamps, which is conceptually wrong, and overlapping issues may occur: seconds from 21:15:05.999 combined by microseconds from 21:15:06.000 give 21:15:05.000.

    Apparently the simplest is to use DateTime::createFromFormat() with U.u, but as stated in a comment, it fails if there are no microseconds.

    So, I'm suggesting this code:

    function udate($format, $time = null) {
    
        if (!$time) {
            $time = microtime(true);
        }
    
        // Avoid missing dot on full seconds: (string)42 and (string)42.000000 give '42'
        $time = number_format($time, 6, '.', '');
    
        return DateTime::createFromFormat('U.u', $time)->format($format);
    }
    

提交回复
热议问题