How to pick the difference in time between two dates using the Carbon plugin, where it shows me whether it is positive or negative

Asked

Viewed 86 times

0

Example:

$primeiraData = Carbon::parse('2019-02-01 13:00:00');
$segundaData =   Carbon::parse('2019-02-02 14:00:00');

$resultado = $segundaData->diffInHours($primeiraData);

Regardless of the order I put the variables it will have the same result "25" in this case. What I need is for you to show me whether that number is positive or negative.

That is to say:

  • from 2019-02-01 13:00:00 until day 2019-02-02 14:00:00 = + 25
  • from 2019-02-02 14:00:00 until day 2019-02-01 13:00:00 = - 25
  • related subject: https://answall.com/questions/269302/diferen%C3%A7a-in-hours-between-days-using-Carbon/269330#269330

1 answer

1

Looking at the Carbon documentation, present in:documentation in the 'Difference' tab, if you pass as the second parameter of the diffInHours function the false value returns the relative value. Thus including the negative sign if the past date is less than the current instance.

Follow the example provided in the documentation link:

$dtOttawa = Carbon::createMidnightDate(2000, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createMidnightDate(2000, 1, 1, 'America/Vancouver');
echo $dtOttawa->diffInHours($dtVancouver);                             // 3
echo $dtVancouver->diffInHours($dtOttawa);                             // 3

echo $dtOttawa->diffInHours($dtVancouver, false);                      // 3
echo $dtVancouver->diffInHours($dtOttawa, false);                      // -3
  • That’s right Ryan, had used the parameter true, but without success. Thanks for the tip, I spent actually reading the documentation.

  • @Murilo if the answer helped you mark as correct.

  • Ryan’s answer is correct and mine helped a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.