我检查了以下问题/回答:如何获得"yyyy-MM-ddTHH:mm:ss"的格式?php中的fffZ " ?响应包括链接到微软文档来格式化日期,但这些在PHP中不起作用。
最上面的答案建议
date('Y-m-dTH:i:s.uZ') //for the current time
这个输出2013-03-22EDT12:56:35.000000-1440016
我正在使用一个API,它需要上面格式的时间戳。API位于英国(GMT),我的服务器位于澳大利亚(AEST)。
API文档中给出的示例要求使用以下格式的日期:
2011-07-15T16:10:45.555Z
2014-07-03T16:41:59+10:00//Notice the Z is replaced with a time diff in hours
我相信'Z'指的是一个区域,但它没有在PHP文档中提到。
不幸的是,当我发布这个格式时,API正在读取时间并占用10个小时。我得到一个错误,说日期不能是过去的(因为它是根据墨尔本的当地时间检查的,但看到的时间早10个小时)。
我已经尝试修剪时间戳以删除API接受的+1000,但记录显示为10小时前创建的。
我需要匹配所需的时间戳,但我找不到任何方法来复制上面的输出,在澳大利亚墨尔本的PHP中。如有任何帮助,不胜感激。
关于SO的第一个问题请让我知道我是怎么做的
Z
表示时区UTC
,并在ISO-8601中定义,这是您所需的输出格式,由毫秒部分扩展。
在输出时间之前,您需要将本地时间转换为UTC:
$dt = new DateTime();
$dt->setTimeZone(new DateTimeZone('UTC'));
则可以使用以下格式字符串:
echo $d->format('Y-m-d'TH-i-s.'0'0'0'Z');
请注意,我已经将毫秒部分归零,并转义了格式模式中的特殊字符T
和Z
。
Z
前的最后3位是时间的小数点后3位,单位为毫秒
函数microtime(true)
给出以毫秒为单位的当前时间,将输出1631882476.298437
在这种情况下,它应该是.298Z
$milliseconds = microtime(true);
// Round to integer
$timestamp = floor($milliseconds);
// Get number after dots
$uuuu = preg_replace("/'d+'./", "", "$milliseconds");
// Get last 3 number decimal place
$u = substr($uuuu, 0, 3);
// Print date by the timestamp timestamp
echo date("Y-m-d'TH:i:s", $timestamp). ".{$u}Z";
$milliseconds = microtime(true);
// Round to integer
$timestamp = floor($milliseconds);
// Get number after dots
$uuuu = preg_replace("/'d+'./", "", "$milliseconds");
// Get last 3 number decimal place
$u = substr($uuuu, 0, 3);
// Print date by the timestamp timestamp
echo date("Y-m-d'TH:i:s", $timestamp). ".{$u}Z";