DateTime with microseconds

后端 未结 10 2119
长发绾君心
长发绾君心 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:37

    This worked for me in PHP 7.2:

    $dateTime = \DateTime::createFromFormat('U.u', sprintf('%f', $aFloat), $optionalTimezone);
    

    I got to thinking that since the format code 'u' would output only the microsecond part of a date when converting to a string then doing the reverse would be the same. And that it also expects a period character '.' so if $aFloat happened to be a whole number then default conversion to a string would leave off the decimal point. Initially I thought the float to string conversion needed '%.6f' but the 'u' is expecting a string which is left justified. Trailing zeros are unnecessary.

提交回复
热议问题