Get interval seconds between two datetime in PHP?

后端 未结 8 1102
孤街浪徒
孤街浪徒 2021-01-31 07:08

2009-10-05 18:11:08

2009-10-05 18:07:13

This should generate 235,how to do it ?

8条回答
  •  生来不讨喜
    2021-01-31 07:18

    If you need the real local time difference and want to work with getTimestamp, you must take DST switches during the calculated period into account. Therefore, the local offset to UTC must be included in the equation.

    Take, for instance, the following dates:

    $tz = new \DateTimeZone("Europe/Berlin");
    $start = new \DateTime("2018-02-01 12:00:00", $tz);
    $end = new \DateTime("2018-04-01 12:00:00", $tz);
    

    $start is "2018-02-01 11:00:00" in UTC, while $end is "2018-04-01 10:00:00" in UTC. Note that, while the time of day is the same in the Berlin timezone, it is different in UTC. The UTC offset is one hour in $start and 2 hours in $end.

    Keep in mind that getTimestamp always returns UTC! Therefore you must subtract the offset from the timestamp when looking for the actual local difference.

    // WRONG! returns 5094000, one hour too much due to DST in the local TZ
    echo $end->getTimestamp() - $start->getTimestamp();
    
    // CORRECT: returns 5090400
    echo ($end->getTimestamp() - $end->getOffset()) - ($start->getTimestamp() - $start->getOffset());
    

提交回复
热议问题