Reputation: 5203
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.
Upvotes: 124
Views: 92049
Reputation: 3252
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);
Upvotes: 9
Reputation: 15415
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();
}
Upvotes: 52
Reputation: 59
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;
}
Upvotes: 5
Reputation: 21249
Could you not compare the time stamps instead?
$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()
Upvotes: 257
Reputation: 16439
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.
Upvotes: 6