Pete
Pete

Reputation: 107

Carbon diffInSeconds() returning negative value

I recently updated nesbot/Carbon from 2.67 to 3.8.6. When running the following piece of code, I used to get a positive value, now I get a negative value. Has the order of operation changed for diffInSeconds()?

$time_before = Carbon::now();
// << call that takes 85 s >>
$time_after = Carbon::now();
$duration_in_secs = $time_after->diffInSeconds($time_before);

This gives me:

Duration: -84.766262 seconds
before:2025-03-02 02:53:35
after:2025-03-02 02:55:00

Upvotes: 1

Views: 34

Answers (1)

KyleK
KyleK

Reputation: 5111

There is an $absolute parameter for this method, it was true by default in 2.x (so you get a positive number whatever was the order).

In 3.x default value is false. When doing from->diffInXyz(to) if from > to, you get a negative value. You can either:

  • swap from and to
  • use abs() function
  • set absolute: true parameter explicitly

Upvotes: 3

Related Questions