Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateInterval object to seconds in php

Tags:

$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

like image 938
sanchitkhanna26 Avatar asked Jan 11 '13 11:01

sanchitkhanna26


2 Answers

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:

$seconds = date_create('@0')->add($interval)->getTimestamp();

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.

like image 160
Brilliand Avatar answered Oct 05 '22 18:10

Brilliand


There is a function format for this. But it wont return the number of seconds. To get number of seconds you use this technique

$seconds = abs($datetime1->getTimestamp()-$datetime2->getTimestamp());

If you really want to use $interval you need to calculate it.

$seconds = $interval->days*86400 + $interval->h*3600 
           + $interval->i*60 + $interval->s;

Here

  • 86400 is the number of seconds in a day
  • 3600 is the number of seconds in an hour
  • 60 is the number of seconds in a minute
like image 44
Shiplu Mokaddim Avatar answered Oct 05 '22 20:10

Shiplu Mokaddim