0

So I'm trying to get the difference in days for the following dates. For one of them it works, but for the other the number is off. It should be 3.

I could use the ceil function, but I still don't know why the following isn't correct.

$checkOut = strtotime('2011-02-16');
$checkIn = strtotime('2011-02-11');
echo ($checkOut - $checkIn) / (60 * 60 * 24); // => 5
echo floor(($checkOut - $checkIn)/(60*60*24)); // => 5

$checkOut = strtotime('2011-03-14');
$checkIn = strtotime('2011-03-11');
echo ($checkOut - $checkIn) / (60 * 60 * 24); // => 2.958333333
echo floor(($checkOut - $checkIn)/(60*60*24)); // => 2
5
  • That is it! Thanks! Although the PHP spec says that strtotime returns seconds since epoch, but I guess that is not the case. Commented Mar 9, 2011 at 22:40
  • Seams to work here ideone.com/ai3jo, outputs 3 for both Commented Mar 9, 2011 at 22:40
  • I get 3 when I do that second block, as expected Commented Mar 9, 2011 at 22:42
  • @James it is returing seconds since epoch, but it is interpreting the input date as being in a certain timezone (which may not be UTC) Commented Mar 9, 2011 at 22:43
  • Ah, good points. Not sure what PHP versions our production systems are using, but assuming it works if I specify UTC, I'll just do that. Commented Mar 9, 2011 at 22:48

3 Answers 3

1

Why not use the php object-oriented DateTime::diff?

<?php
$datetime1 = new DateTime('2011-03-11');
$datetime2 = new DateTime('2011-03-14');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
Sign up to request clarification or add additional context in comments.

Comments

0

You may want to use DateTime::diff() for that problem.

By using floor() you're essentially getting the next lower integer (cutting away everything after the comma).

Comments

0

So the problem is because it crosses daylight savings time. Although the PHP spec says that strtotime returns seconds since epoch, I guess that is not the case.

2 Comments

Uhm, of course it returns the seconds since epoch. The switch from/to DST makes one day 3600 seconds shorter/longer, so those 3600 seconds are missing in that "seconds since epoch".
Um... I don't believe that is true, even according to the definition that I gave. en.wikipedia.org/wiki/Unix_time

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.