php get microtime from date string

前端 未结 2 826
[愿得一人]
[愿得一人] 2020-12-07 00:29

I am trying to get the time passed between two datetime strings (including milliseconds)

example:

$pageTime = strtotime(\"2012-04-23T16:08:14.9-05:00         


        
2条回答
  •  感动是毒
    2020-12-07 01:11

    Building on Dan Lee's answer, here's a universally working solution:

    $pageTime = new DateTime("2012-04-23T16:08:14.9-05:00");
    $rowTime  = new DateTime("2012-04-23T16:08:16.1-05:00");
    
    $uDiff = ($rowTime->format('u') - $pageTime->format('u')) / (1000 * 1000);
    
    $timePassed = $rowTime->getTimestamp() - $pageTime->getTimestamp() + $uDiff;
    

    Complete explanations:

    • We store the signed microseconds difference between both dates in $uDiff and convert the result in seconds by dividing by 1000 * 1000
    • The order of the operands in $uDiff is important and has to be the same as in the $timePassed operation.
    • We compute the Unix timestamp (in full seconds) difference between both dates and we add the microseconds difference to get the wanted result
    • Using DateTime::getTimestamp() will give a correct answer even when the difference is greater than 60 seconds

提交回复
热议问题