1

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";
NotoriousWebmaster
  • 3,298
  • 7
  • 37
  • 49

2 Answers2

1

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;
}
NotoriousWebmaster
  • 3,298
  • 7
  • 37
  • 49
0

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";
Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • how do you get from the ISO 8601 date to the $interval? – NotoriousWebmaster Oct 01 '13 at 15:00
  • @NotoriousWebmaster The code from the answer was meant to be a snippet you can integrate into your code to add the microseconds. I've updated the answer so you can see where it would go – Bogdan Oct 01 '13 at 18:38