php 以微秒为单位的日期时间

php datetime in microseconds

我有以下格式的日期 2016-10-16T22:12:45.104Z 这些日期然后由我正在使用的 api SDK 转换为日期时间对象。

我想要做的是将日期时间对象作为与“2016-10-16T22:12:45.104Z”完全相同的字符串获取,它必须是准确的字符串,以便我可以将其传递给另一个函数。

我在此处的另一个答案中找到了以下 php 脚本,但这是当前时间。

我已经尝试过诸如 ->format('U') 之类的方法,但没有任何效果,我需要获取与我认为的 microtime(true) 格式相同的日期时间对象。

如何在我拥有的日期上使用下面的 php 代码,以便它们可以像“2016-10-16T22:12:45.104Z”一样被回显?

<?php
$time = microtime(true);
$tMicro = sprintf("%03d",($time - floor($time)) * 1000);
$tUtc = gmdate('Y-m-d\TH:i:s.', $time).$tMicro.'Z';
echo $tUtc;
?>

如您在文档中所见,'u' 在这种情况下非常有用。 http://php.net/manual/en/class.datetime.php#118608

您应该可以使用此解决方案 "Y-m-d\TH:i:s.u\Z",但不幸的是您需要毫秒而不是微秒,结果多了 3 个 0。要解决此问题,只需将 'u' 的结果除以 1000。

$dt = new DateTime('2016-10-16T22:12:45.104Z');
$helper = $dt->format('u'); //this is factor of 1000 off
$helper /= 1000 
$ans = $dt->format('Y-m-d\TH:i:s'); //get the first part of what you
$ans .= "." . $helper . "Z"; //add the milliseconds back on, and Z for good measure

echo $ans . "\n";