DateTime with microseconds

后端 未结 10 2123
长发绾君心
长发绾君心 2020-12-05 10:02

In my code, I\'m using DateTime objects to manipulate dates, then convert them to timestamp in order to save them in some JSON files.

For some reasons,

10条回答
  •  醉话见心
    2020-12-05 10:32

    Here's a very simple method of creating a DateTime object that includes microtime.

    I didn't delve into this question too deeply so if I missed something I apologize but hope you find this helpful.

    $date = DateTime::createFromFormat('U.u', microtime(TRUE));
    var_dump($date->format('Y-m-d H:i:s.u')); 
    

    I tested it out and tried various other ways to make this work that seemed logical but this was the sole method that worked for PHP versions prior to 7.1.

    However there was a problem, it was returning the correct time portion but not the correct day portion (because of UTC time most likely) Here's what I did (still seems simpler IMHO):

    $dateObj = DateTime::createFromFormat('U.u', microtime(TRUE));
    $dateObj->setTimeZone(new DateTimeZone('America/Denver'));
    var_dump($dateObj->format('Y-m-d H:i:s:u'));
    

    Here's a working example: http://sandbox.onlinephpfunctions.com/code/66f20107d4adf87c90b5c8c914393d4edef180a2

    UPDATE
    As pointed out in comments, as of PHP 7.1, the method recommended by Planplan appears to be superior to the one shown above.

    So, again for PHP 7.1 and later it may be better to use the below code instead of the above:

    $dateObj = DateTime::createFromFormat('0.u00 U', microtime());
    $dateObj->setTimeZone(new DateTimeZone('America/Denver'));
    var_dump($dateObj->format('Y-m-d H:i:s:u'));
    

    Please be aware that the above works only for PHP versions 7.1 and above. Previous versions of PHP will return 0s in place of the microtime, therefore losing all microtime data.

    Here's an updated sandbox showing both: http://sandbox.onlinephpfunctions.com/code/a88522835fdad4ae928d023a44b721e392a3295e

    NOTE: in testing the above sandbox I did not ever see the microtime(TRUE) failure which Planplan mentioned that he experienced. The updated method does, however, appear to record a higher level of precision as suggested by KristopherWindsor.

    NOTE2: Please be aware that there may be rare cases where either approach will fail because of an underlying decision made regarding the handling of microseconds in PHP DateTime code. Either:

    • avoid use of this for scientific purposes or anything where a very high level of accuracy is required.
    • OR be prepared for no microsecond data to return on an exact second mark... (where a microsecond ... which is 1 millionth of a second, will have no data to return as it is complete zeros... from what I've read this is not clear from what's returned and could be done in a better way but is worth creating code to handle ... again, for high precisions uses)

    Thanks for the headsup Sz. (see comments).

提交回复
热议问题