0

I used the approved answer to this question but carbon does not calculate time correctly.

laravel-how-to-convert-time-in-seconds-to-human-readable

Why the output of the following codes is different?

$sec = 17279645;
Carbon::now()->addSeconds($sec)->diffForHumans(false, ['parts' => 5]);
CarbonInterval::seconds($sec)->cascade()->forHumans();


"6 months 2 weeks 3 days 54 minutes 4 seconds after"
"7 months 3 days 23 hours 54 minutes 5 seconds"
omid
  • 400
  • 3
  • 19
  • [You can do this here](https://stackoverflow.com/a/19680778/3536236) (Dupe question). – Martin May 31 '22 at 10:09
  • I prefer use locales supported by Carbon – omid May 31 '22 at 10:13
  • For example, 6 months or 7 months depends entirely on *which* month's your dealing with as months have different day counts. – Martin May 31 '22 at 10:17
  • Your answer will have a different coding for each language, such as English, French, etc. My goal is to use the carbon translation feature. – omid May 31 '22 at 10:21

1 Answers1

1

CarbonInterval::cascade() use simple static factors:

[
    'milliseconds' => [1000, 'microseconds'],
    'seconds' => [1000, 'milliseconds'],
    'minutes' => [60, 'seconds'],
    'hours' => [60, 'minutes'],
    'dayz' => [24, 'hours'],
    'weeks' => [7, 'dayz'],
    'months' => [4, 'weeks'],
    'years' => [12, 'months'],
]

The same number of seconds always give the same output.

While diffForHumans takes the "now" into account, months will actually have 28, 30 or 31 days, (a day can be 25 hours if you have DST in your interval etc.) so the same amount of seconds gives you variable output depending on the current time.

About the 1 second difference, it's because between the moment you do Carbon::now() and the moment you do diffForHumans() few microseconds elapsed. So your interval is actually something like 17279644.987 instead of exactly 17279645.

KyleK
  • 4,643
  • 17
  • 33