$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
How do i convert the above $interval
to seconds in php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
How do i convert the above $interval
to seconds in php
There is a function
format
for this. But it wont return the number of seconds. To get number of seconds you use this techniqueIf you really want to use
$interval
you need to calculate it.Here
86400
is the number of seconds in a day3600
is the number of seconds in an hour60
is the number of seconds in a minuteI would only add to shiplu's answer:
To handle negative intervals.
Note that - contrary to Brilliand's answer - The code above will consider correctly years, months and dates. Because $interval->days is an absolute value ($interval->d is relative to the month).
EDIT: this function is still not correct, as pointed out by @Brilliand. A counter-example is
It doesn't handle months well.
Another way to get the number of seconds in an interval is to add it to the zero date, and get the timestamp of that date:
This method will handle intervals created via the DateInterval contructor more or less correctly, whereas shiplu's answer will ignore years, months and days for such intervals. However, shiplu's answer is more accurate for intervals that were created by subtracting two dates. For intervals consisting only of hours, minutes and seconds, both methods will get the correct answer.