tags:

views:

50

answers:

3

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.

A: 

You could just put in the hard numbers (instead of 60*60 - put in 3600) so it doesn't need to calculate them each time.

Edit - fixed the number based off your comment.

Duniyadnd
That'd be fine, and it would probably run a fraction of a second faster in PHP, but it still leaves me with the same mis-calculation as the example above.
efritz
+2  A: 

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.

xil3
+3  A: 

Could you not compare the time stamps instead?

$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()
Ben
I guess I didn't RTFM... This is what I was looking for; thanks a lot!
efritz