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 | 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 )
The span of time between a specific start date and end date.
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.
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.
Could you not compare the time stamps instead?
$now = new DateTime('now'); $diff = $date->getTimestamp() - $now->getTimestamp()
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With