Get interval seconds between two datetime in PHP?

✔ Recommended Answer

You can use strtotime() to do that:

$diff = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')

A similar approach is possible with DateTime objects, e.g.

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

Source: stackoverflow.com

Answered By: Paul Dixon

Method #2

To get the interval in seconds between two dates in PHP, you can use the DateTime class to create two DateTime objects representing the start and end dates, and then calculate the difference between them using the diff() method. Here's an example:

php
$start = new DateTime('2023-04-16 10:00:00'); $end = new DateTime('2023-04-16 10:01:30'); $interval = $end->diff($start); $seconds = $interval->s + ($interval->i * 60) + ($interval->h * 3600) + ($interval->d * 86400); echo $seconds; // Output: 90

In this example, we create two DateTime objects representing the start and end times. We then call the diff() method on the end date, passing in the start date as an argument. This returns a DateInterval object representing the difference between the two dates.

We then calculate the total number of seconds in the interval by adding up the seconds, minutes, hours, and days components of the interval using simple arithmetic. Finally, we output the total number of seconds.

Note that the diff() method returns a DateInterval object that includes many different properties, including years, months, days, hours, minutes, and seconds. In this example, we only use the seconds, minutes, hours, and days components, but you can use any of the properties that are relevant to your use case.

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755