Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Interval can return negative zero or positive zero how can I set a conditional statement on the result

Given the $interval is a DateInterval object following conditional statement is true whether the anniversary is within 1 year prior to the current date = 0 or the anniversary is within 1 year post the current date = -0.

$interval = $anniversary->diff($current_Date);
if ($interval->format('%r%y') < 0){
    do something
}
  • I can't use abs because they are both 0
  • I can't use <= 0 because they both are
  • I can't use >= 0 because this sets to true on other cases which I don't want
  • I can't use < 0 because 0 isn't and I want 0 to be true
  • I can't use == 0 because both are true
  • I can't use > 0 because 0 isn't and I want 0 to be true

So I want to be able to say something like is this number signed negative but no such thing exists as far as I can tell. Any thoughts?

** Edit **

The solution is to compare the date objects and decide if they are in the appropriate DateInterval:

if ($anniversary < $current_Date && $interval->format('%r%y') == 0){
like image 687
codepuppy Avatar asked Nov 19 '25 23:11

codepuppy


1 Answers

As the returned value of DateTime::diff() is a DateInterval object, the solution is to use the DateInterval::invert property:-

$interval = $anniversary->diff($current_Date);
if ($interval->invert){
    //do something
}

To quote the manual:-

invert

Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format().

like image 75
vascowhite Avatar answered Nov 22 '25 12:11

vascowhite