Home » Php » php – Why does datetime->days always returns a positive number

php – Why does datetime->days always returns a positive number

Posted by: admin April 23, 2020 Leave a comment

Questions:
// 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?

How to&Answers:

You could use DateInterval::format.

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

Cast to int if needed:

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

Answer:

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

$invert    = $interval->invert; 

Answer:

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

Answer:

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

Answer:

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.