Search code examples
phpdatetimeunix-timestampmillisecondsmicrotime

PHP Converting ASCII Date/Time Stamps to Unix Times With Microseconds


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

Solution

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