PHP使用微秒将ASCII日期/时间戳转换为Unix时间

时间:2013-09-30 19:24:10

标签: php datetime unix-timestamp milliseconds microtime

我有两个ASCII日期时间戳。最终我希望得到秒和毫秒的差异。我尝试过使用DateTime类以及Date()函数。这两个似乎都截断了微秒,即使日期格式的文档说该类保留了它。

这是我到目前为止所得到的:

<?php
// test.datetimediff.php

echo "<pre>\n";

$tz = new DateTimeZone('America/Toronto');
echo print_r($tz, true) . "<br>\n";

/*
$dt1 = date('Y-m-d H:i:s.u', '2013-09-30 13:06:56.944');
$dt2 = date('Y-m-d H:i:s.u', '2013-09-30 13:06:56.979');
*/

$dt1 = new Datetime('2013-09-30 13:06:56.944', $tz);
$dt2 = new Datetime('2013-09-30 13:06:56.979', $tz);

echo print_r($dt1, true) . "<br>\n";
echo print_r($dt2, true) . "<br>\n";

$interval = $dt1->diff($dt2);

$seconds = $interval->format('%s');

echo 'seconds: ' . $seconds . "<br>\n";

echo "</pre>\n" . "<br>\n";

2 个答案:

答案 0 :(得分:1)

无法找到考虑microtime的功能。所以我将它转换为直线整数秒,并在几毫秒内自行添加。这是我设置的功能:

/*
expects $datetime in format yyyy-mm-ddThh:mm:ss.9999
*/
function strtomtime($datetime) {

    $dt1 = strtotime($datetime);
    $pos = strrpos($datetime, '.');
    $mtime = $dt1 + floatval(substr($datetime, $pos));
    return $mtime;
}

答案 1 :(得分:0)

这是一种可行的解决方法。不是最漂亮的,尽管它起到了作用:

<?php
// test.datetimediff.php

echo "<pre>\n";

$tz = new DateTimeZone('America/Toronto');
echo print_r($tz, true) . "<br>\n";

/*
$dt1 = date('Y-m-d H:i:s.u', '2013-09-30 13:06:56.944');
$dt2 = date('Y-m-d H:i:s.u', '2013-09-30 13:06:56.979');
*/

$dt1 = new Datetime('2013-09-30 13:06:56.944', $tz);
$dt2 = new Datetime('2013-09-30 13:06:56.979', $tz);

echo print_r($dt1, true) . "<br>\n";
echo print_r($dt2, true) . "<br>\n";

$interval = $dt1->diff($dt2);

$seconds = (int) $interval->format('%s');

// Get microseconds from both start and end date
$us1 = $dt1->format('u');
$us2 = $dt2->format('u');

// Compute the microsecond difference and add it to the seconds
$seconds += abs($us2 - $us1) / 1000000;

echo 'seconds: ' . $seconds . "<br>\n";

echo "</pre>\n" . "<br>\n";