3

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?

1
  • I would like to see how you get the exact number anything above days. Commented Jun 20, 2010 at 11:56

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)
Glad to help and I'm very happy to see people using PHP 5.3 in production :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.