Mar 12, 2013 - Development    Comments Off

PHP date_diff days negative zero issue

I ran into an odd problem today that I couldn’t find a solution to when searching Google. I ended up figuring it out and thought I should document it here for future searches.

PHP has a date_diff function from v5.3+. I was using this function to calculate the difference in DAYS between two dates. I found that the results I received did not match what I expected. PHP says the difference between Yesterday and Today is -1 (negative one) days. The difference between Today and Today is -0 (negative zero) days. The difference between Tomorrow and Today is 0 (zero) days. And the difference between Today and the Day After Tomorrow is 1 (one) day, etc. Say whaaaaat?

Duplicate this:

$day1 = new DateTime();
$day2 = new DateTime("yesterday");
$interval = $day1->diff($day2);
$interval = date_diff($day1, $day2);
$days = $interval->format('%r%a');
//%r = show negative sign or nothing
//%a = number of total days

echo "$days <br/>";

$day2 = new DateTime("today");
$interval = $day1->diff($day2);
$interval = date_diff($day1, $day2);
$days = $interval->format('%r%a');

echo "$days <br/>";

$day2 = new DateTime("tomorrow");
$interval = $day1->diff($day2);
$interval = date_diff($day1, $day2);
$days = $interval->format('%r%a');
echo "$days <br/>";

In order to get a difference value that I expected I had to write a statement to convert these values. I also ran into some odd comparison issues and had to resort to using === to compare the days. Even though I compared string to string I kept getting false positives. I threw together a quick conversion if/then/else that created the right type of “days” value for what I was expecting:

if($days === "-0")
{
//today
$days = 0;
}
elseif($days === "0")
{
//tomorrow
$days = 1;
}
elseif($days > 0)
{
$days = $days + 1;
}

PHP handled the other days in the past as expected, for whatever reason. The day before yesterday is -2 without any modifications.

Comments Closed

Comments are closed.