I have two ASCII date time stamps. Ultimately I want to get the difference in seconds and milliseconds. I've tried using the DateTime class, as well as the Date() function. Both of these seem to truncate the microseconds, even though the docs for date formats say the class keeps it.

Here's what I've got so far:

<?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

This is a possible workaround. Not the prettiest, though it does the job:

<?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";

其他提示

Couldn't find a function which would take microtime into account. So I converted it to straight integer seconds, and tacked on the milliseconds myself. Here's the function I set up:

/*
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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top