Get interval seconds between two datetime in PHP?

Viewed 123051

2009-10-05 18:11:08

2009-10-05 18:07:13

This should generate 235,how to do it ?

9 Answers

For those worrying about the limitations of using timestamps (i.e. using dates before 1970 and beyond 2038), you can simply calculate the difference in seconds like so:

$start = new DateTime('2009-10-05 18:11:08');
$end = new DateTime('2009-10-05 18:07:13');
$diff = $end->diff($start);

$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->h * 60 * 60;
$minsInSecs = $diff->i * 60;

$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->s;

echo $seconds; // output: 235

Wrote a blog post for those interested in reading more.

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());

The solution proposed by @designcise is wrong when "end date" is before "start date". Here is the corrected calculation

$diff = $start->diff($end);

$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->format('%r%h') * 60 * 60;
$minsInSecs = $diff->format('%r%i') * 60;

$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->format('%r%s');

A simple and exact solution (exemplifying Nilz11's comment):

$hiDate = new DateTime("2310-05-22 08:33:26");
$loDate = new DateTime("1910-11-03 13:00:01");
$diff = $hiDate->diff($loDate);
$secs = ((($diff->format("%a") * 24) + $diff->format("%H")) * 60 + 
   $diff->format("%i")) * 60 + $diff->format("%s");
Related