如何使用PHP的date()
函数使用以下16位数时间戳(来自XML文件)?
1295076698126000 // 15-01-2011 08:31:38.126
1286697695521000 // 10-10-2010 10:01:35.521
答案 0 :(得分:5)
这些时间戳以微秒为单位。但是,由于PHP使用date()
在几秒钟内使用整数作为时间戳,因此您将无法获得微秒值。您仍然可以通过将时间戳除以百万(100万微秒= 1秒)并将商传递给date()
来打印剩余的日期:
// "u" will always be printed as 000000 regardless of actual microseconds
echo date('d-m-Y H:i:s.u', 1295076698126000 / 1000000);
编辑: Hacky,但您可以执行手动算法来获取毫秒并单独输出它作为解决方法,如下所示:
$xml_timestamp = 1295076698126000;
$seconds = $xml_timestamp / 1000000;
$microseconds = $seconds - floor($seconds);
$seconds = floor($seconds);
// 1 millisecond = 1000 microseconds
// Milliseconds, because your desired output is 3 decimal places long, not 6
$milliseconds = round($microseconds * 1000);
$format = 'd-m-Y H:i:s.' . sprintf('%03d', $milliseconds);
echo date($format, $seconds);
对于可重用性,DateTime
类是一个不错的选择。或者,自定义功能:
function date_milliseconds($format, $timestamp = NULL) {
$seconds = ($timestamp === NULL) ? microtime(true) : $timestamp / 1000000;
$microseconds = $seconds - floor($seconds);
$seconds = floor($seconds);
$milliseconds = round($microseconds * 1000);
$format = preg_replace('/(?<!\\\\)u/', sprintf('%03d', $milliseconds), $format);
return date($format, $seconds);
}
echo date_milliseconds('d-m-T H:i:s.u', floatval($xml_timestamp));