How to get millisecond between two dateTime obj?

前端 未结 5 451
南方客
南方客 2020-12-11 18:06

How to get millisecond between two DateTime objects?

$date = new DateTime();
$date2 = new DateTime(\"1990-08-07 08:44\");

I t

5条回答
  •  -上瘾入骨i
    2020-12-11 18:41

    Sorry to digg out an old question, but I've found a way to get the milliseconds timestamp out of a DateTime object:

    function dateTimeToMilliseconds(\DateTime $dateTime)
    {
        $secs = $dateTime->getTimestamp(); // Gets the seconds
        $millisecs = $secs*1000; // Converted to milliseconds
        $millisecs += $dateTime->format("u")/1000; // Microseconds converted to seconds
        return $millisecs;
    }
    

    It requires however that your DateTime object contains the microseconds (u in the format):

    $date_str = "20:46:00.588";
    
    $date = DateTime::createFromFormat("H:i:s.u", $date_str);
    

    This is working only since PHP 5.2 hence the microseconds support to DateTime has been added then.

    With this function, your code would become the following :

    $date_str = "1990-08-07 20:46:00.588";
    $date1 = DateTime::createFromFormat("Y-m-d H:i:s.u", $date_str);
    
    $msNow = (int)microtime(true)*1000;
    
    echo $msNow - dateTimeToMilliseconds($date1);
    

提交回复
热议问题