views:

42

answers:

1

I'm a bit stuck with the DateInterval class of PHP. What I really want is the number of seconds elapsed between two DateTime stamps.

$t1 = new DateTime( "20100101T1200" );
$t2 = new DateTime( "20100101T1201" );
// number of seconds between t1 and t2 should be 60

echo "difference in seconds: ".$t1->diff($t2)->format("%s");

Yet all I get is zero. Is the DateInterval class not suited for arithmetic? How can I get the 'exact' number of seconds (or hours, or whatever) between two time stamps?

+6  A: 

If you just want the seconds quickly you might aswell use

$diff = abs($t1->getTimestamp() - $t2->getTimestamp());

Your code returns 0, because the actual seconds difference is 0, the difference in your example is 1 minute (1 minute, 0 seconds). If you print the %i format, you will get 1, which is the correct diff of $t1 and $t2.

Denis 'Alpheus' Čahuk
Thanks! I was so happy with the type-safe `DateInterval`: you can't add anything but that to a `DateTime`, which is great. But this does the trick. (And on PHP 5.2, you can use `DateTime::format("U")` to retrieve the number of seconds since the epoch)
xtofl
Glad to help and I'm very happy to see people using PHP 5.3 in production :)
Denis 'Alpheus' Čahuk