Why does datetime->days always returns a positive number

PhpDatetime

Php Problem Overview


// Difference from a date in the future:
$a = new DateTime('2000-01-01');
$b = new DateTime('2000-01-05');
$interval = $b->diff($a);
return $interval->days;             // Returns 4


// Difference from a date in the past:
$a = new DateTime('2000-01-01');
$b = new DateTime('1999-12-28');
$interval = $a->diff($b);           // Arguments swapped
return $interval->days;             // Returns 4

Why do both of these functions return positive 4? How do I return a negative number if a date is in the past?

Php Solutions


Solution 1 - Php

You could use DateInterval::format.

return $interval->format("%r%a");

Cast to int if needed:

return (int)$interval->format("%r%a");

Solution 2 - Php

If Date is in past then invert will 1.
If Date is in future then invert will 0.

$invert    = $interval->invert; 

Solution 3 - Php

Here is your answer:

$today = new DateTime();
$date = new DateTime('2013-03-10');
$interval = $today->diff($date);
echo $interval->format("%r%a");

Test it here

Solution 4 - Php

When you are diffing two DateTime objects, the following rule applies:

$objA->diff($objB) == $objB - $objA

As an example:

$todayDateObj = new \DateTime('2016/5/26');
$foundedDateObj = new \DateTime('1773/7/4');
    
$interval = $todayDateObj->diff($foundedDateObj);
echo $interval->format('%r%a') . "\n\n";
// -88714
    
$interval2 = $foundedDateObj->diff($todayDateObj);
echo $interval2->format('%r%a');
// 88714

Solution 5 - Php

you can use timestamp like this.

<?php 
    $date1 = '2015-01-02';
    $date2 = '2015-01-05';
    $diff = strtotime($date1, 'Y-m-d') - strtotime($date2, 'Y-m-d'); 
?>

$diff will return negative or positive.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonoBView Question on Stackoverflow
Solution 1 - PhplaforView Answer on Stackoverflow
Solution 2 - PhpGurudutt SharmaView Answer on Stackoverflow
Solution 3 - PhpMehdi KaramoslyView Answer on Stackoverflow
Solution 4 - PhpJay ShethView Answer on Stackoverflow
Solution 5 - PhpyussanView Answer on Stackoverflow