Calculate total seconds in PHP DateInterval

PhpDatetimeDate

Php Problem Overview


What is the best way to calculate the total number of seconds between two dates? So far, I've tried something along the lines of:

$delta   = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;

However, the days property of the DateInterval object seems to be broken in the current PHP5.3 build (at least on Windows, it always returns the same 6015 value). I also attempted to do it in a way which would fail to preserve number of days in each month (rounds to 30), leap years, etc:

$seconds = ($delta->s)
         + ($delta->i * 60)
         + ($delta->h * 60 * 60)
         + ($delta->d * 60 * 60 * 24)
         + ($delta->m * 60 * 60 * 24 * 30)
         + ($delta->y * 60 * 60 * 24 * 365);

But I'm really not happy with using this half-assed solution.

Php Solutions


Solution 1 - Php

Could you not compare the time stamps instead?

$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()

Solution 2 - Php

This function allows you to get the total duration in seconds from a DateInterval object

/**
 * @param DateInterval $dateInterval
 * @return int seconds
 */
function dateIntervalToSeconds($dateInterval)
{
    $reference = new DateTimeImmutable;
    $endTime = $reference->add($dateInterval);

    return $endTime->getTimestamp() - $reference->getTimestamp();
}

Solution 3 - Php

You could do it like this:

$currentTime = time();
$timeInPast = strtotime("2009-01-01 00:00:00");

$differenceInSeconds = $currentTime - $timeInPast;

time() returns the current time in seconds since the epoch time (1970-01-01T00:00:00), and strtotime does the same, but based on a specific date/time you give.

Solution 4 - Php

static function getIntervalUnits($interval, $unit)
{
	// Day
	$total = $interval->format('%a');
	if ($unit == TimeZoneCalc::Days)
		return $total;
	//hour
	$total = ($total * 24) + ($interval->h );
	if ($unit == TimeZoneCalc::Hours)
		return $total;
	//min
	$total = ($total * 60) + ($interval->i );
	if ($unit == TimeZoneCalc::Minutes)
		return $total;	
	//sec
	$total = ($total * 60) + ($interval->s );
	if ($unit == TimeZoneCalc::Seconds)
		return $total;	
	
	return false;
}

Solution 5 - Php

DateTime::diff returns a DateInterval object between 2 dates.

The DateInterval object gives all the informations (the number of days, hours, minutes, seconds).

Here's a sample code:

/**
 * intervalToSeconds
 *
 * @param  DateInterval $interval
 * @return int
 */
function intervalToSeconds(\DateInterval $interval) {
    return $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s;
}

$date_1 = new \DateTime('2021-03-03 05:59:19');
$date_2 = new \DateTime('now');
$interval = $date_1->diff($date_2);
echo intervalToSeconds($interval);

Solution 6 - Php

It always feels nice when what you need is already present as a class. In your case, you need a total number of seconds. Why not make a class out of that? The code could look like that:

(new TotalFullSeconds(
    new IntervalFromRange(
        new DateTimeFromISO8601String('2017-07-03T14:27:39+00:00'),
        new DateTimeFromISO8601String('2017-07-05T14:27:39+00:00')
    )
))
    ->value()

Besides being intuitive, you can also benefit from autocompletion facility of your IDE.

For more useful implementation, you can check out this library.

Solution 7 - Php

You could just put in the hard numbers (instead of 60*60 - put in 3600) so it doesn't need to calculate them each time.

Edit - fixed the number based off your comment.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionefritzView Question on Stackoverflow
Solution 1 - PhpBenView Answer on Stackoverflow
Solution 2 - Phpdave1010View Answer on Stackoverflow
Solution 3 - Phpxil3View Answer on Stackoverflow
Solution 4 - PhphoofuzView Answer on Stackoverflow
Solution 5 - PhpmigliView Answer on Stackoverflow
Solution 6 - PhpVadim SamokhinView Answer on Stackoverflow
Solution 7 - PhpDuniyadndView Answer on Stackoverflow