How to Get the Date/Time Difference in Seconds Between Two DateTime Objects in PHP?

By default there's no method available on the DateTime or DateInterval class to get the difference between two DateTime objects in seconds. Therefore, you can either get the difference of the timestamps of the two dates or calculate the number of seconds yourself:

Comparing Timestamps to Get Number of Seconds Between Two Dates

We can simply compare timestamps of two dates to get the difference in seconds. For example:

$start = new DateTime('2011-12-31 00:00:00');
$end = new DateTime('2021-01-01 00:00:00');

echo $end->getTimestamp() - $start->getTimestamp(); // output: 284169600

Please note that comparing timestamps could lead to problems with dates before 1970 and after 2038.

Calculating Number of Seconds Between Two Dates

You can calculate the number of seconds between the two dates in the following way:

$start = new DateTime('2011-12-31 00:00:00');
$end = new DateTime('2021-01-01 00:00:00');
$diff = $start->diff($end);

$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: 284169600

The calculation works in the following way:

  • Using the %r formatting character, adds the minus sign when the result is negative;
  • Using the %a formatting character gives us the total number of days between two dates;
  • Using the %r%a format together, we can get the negative/positive number of days. Using that, we can convert the number of days into seconds by multiplying it with hours in a day, minutes in an hour, and seconds in a minute (i.e. days * 24 * 60 * 60);
  • The calculation in the last step does not take into account the hours, minutes and seconds in the date difference (as they're not included in the %a format). To include those, we simply use the hour, minute and second properties available on the DateInterval object and convert them into seconds as shown in the example above.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.