0

I'm trying to calculate the difference between two different hours. Everything work fine! I create a function that return me the H:i:s

function dateDifference($date_1 , $date_2 , $differenceFormat = '%r%a' ) {
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);
    $interval->format('%r%a');

    return $interval->format('%r%H:%i:%s');;
}

print dateDifference(date('H:i:s'), $orariof); ///$orariof is any time

This is the result: https://i.postimg.cc/0565G9c3/Immagine-2022-10-31-165134.png

But if I try to add the following if statement, the condition becomes true for the right options, except for one. If anyone could help me understand why the condition become true for the exception, I really appreciate it!

The function:

if(dateDifference(date('H:i:s'), $orariof)>date('H:i:s', strtotime('00:30:00'))){
  print dateDifference(date('H:i:s'), $orariof);
}

And the result: https://i.postimg.cc/y830wq1r/Immagine-2022-10-31-165104.png

The if statement print a time difference which shouldn't be printed because the difference is only 9 minutes

6
  • It isn't at all clear what you are trying to show us in the images. It would be best if you edited your question and include the results directly instead of as an image. Commented Oct 31, 2022 at 16:45
  • The if statement print a time difference which shouldn't be printed because the difference is only 9 minutes Commented Oct 31, 2022 at 16:56
  • The function doesn't actually do anything with the $minutes variable, should it? Commented Oct 31, 2022 at 17:22
  • The $minutes variable doesn't do anything, I'll remove it now Commented Oct 31, 2022 at 17:30
  • 1
    You are returning the result of DateTime::format which is a string, and then are trying to perform string comparison logic on this which could be very fragile. You are also return both a full date and time using r, as well as the time in hours, minutes and seconds. Lastly, you are using % syntax which isn't used in formatting of dates and instead brought over literally: 3v4l.org/9JXKc Commented Oct 31, 2022 at 17:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.