Home > database >  How to convert time in seconds Larger than 86400 to human readable by Carbon API extension
How to convert time in seconds Larger than 86400 to human readable by Carbon API extension

Time:06-01

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"

CodePudding user response:

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.

  • Related