James
James

Reputation: 1

PHP Date / Time Problem

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

Upvotes: 0

Views: 721

Answers (3)

James
James

Reputation: 1

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.

Upvotes: 0

Bogdan Constantinescu
Bogdan Constantinescu

Reputation: 5356

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');

Upvotes: 1

halfdan
halfdan

Reputation: 34244

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).

Upvotes: 0

Related Questions