Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate total seconds in PHP DateInterval

Tags:

date

php

datetime

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.

like image 818
efritz Avatar asked Jul 04 '10 23:07

efritz


People also ask

What is DateInterval in PHP?

PHP | DatePeriod getDateInterval() Function The DatePeriod::getDateInterval() function is an inbuilt function in PHP which is used to return the date interval for the given date period. Syntax: DateInterval DatePeriod::getDateInterval( void )

What is DateInterval?

The span of time between a specific start date and end date.

How will you get the difference between 2 DateTime values in seconds in PHP?

1 Answer. Show activity on this post. $timeFirst = strtotime('2011-05-12 18:20:20'); $timeSecond = strtotime('2011-05-13 18:20:20'); $differenceInSeconds = $timeSecond - $timeFirst; You will then be able to use the seconds to find minutes, hours, days, etc.

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


2 Answers

Could you not compare the time stamps instead?

$now = new DateTime('now'); $diff = $date->getTimestamp() - $now->getTimestamp() 
like image 101
Ben Avatar answered Oct 14 '22 12:10

Ben


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(); } 
like image 26
dave1010 Avatar answered Oct 14 '22 12:10

dave1010