开发者

16-digit timestamp with PHPs date() function

How can I use the following 1开发者_运维百科6-digit timestamp (from an XML file) with PHP's date() function?

1295076698126000  // 15-01-2011 08:31:38.126
1286697695521000  // 10-10-2010 10:01:35.521


Those timestamps are in microseconds. However, since PHP uses integers for timestamps in seconds with date(), you won't be able to obtain the microsecond value. You're still able to print the rest of the date by dividing the timestamp by a million (1 million microseconds = 1 second), and passing the quotient to date():

// "u" will always be printed as 000000 regardless of actual microseconds
echo date('d-m-Y H:i:s.u', 1295076698126000 / 1000000);

EDIT: Hacky, but you can perform manual arithmetic to get the milliseconds and output it separately as a workaround, like this:

$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);

For reusability the DateTime class is a good option. Or, a custom function:

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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜