Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime diff negative result?

Tags:

php

datetime

I have a php code to use calculate different of two DateTime objects, using date_diff procedure. At times the result is negative but it show positive always.

Code example:

  $time1 = new DateTime('01:00:00');
  $time2 = new DateTime('02:00:00');
  $resultTime = date_diff($time1, $time2);
  echo "RESULT: ".$resultTime->format('%h'); // 1

Im expecting -1 here, yet I always get positive 1. Is it possible to show the 'real' result, negative or positive?

like image 662
ruzD Avatar asked Nov 09 '16 09:11

ruzD


1 Answers

$resultTime->format('%r%H:%i:%s'); is what you're looking for. %r prints a minus sign if the difference is negative, or nothing if it is positive. You can also use $resultTime->invert, which equals to 1 if the difference is negative.

like image 67
Pierre-Loup Pagniez Avatar answered Nov 07 '22 09:11

Pierre-Loup Pagniez