PHP DateTime microseconds always returns 0

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

    \DateTime::createFromFormat('U.u', microtime(true));
    

    Will give you (at least on most systems):

    object(DateTime)(
      'date' => '2015-03-09 17:27:39.456200',
      'timezone_type' => 3,
      'timezone' => 'Australia/Darwin'
    )
    

    But there is a loss of precision because of PHP float rounding. It's not truly microseconds.

    Update

    This is probably the best compromise of the createFromFormat() options, and provides full precision.

    \DateTime::createFromFormat('0.u00 U', microtime());
    

    gettimeofday()

    More explicit, and maybe more robust. Solves the bug found by Xavi.

    $time = gettimeofday(); 
    \DateTime::createFromFormat('U.u', sprintf('%d.%06d', $time['sec'], $time['usec']));
    

提交回复
热议问题