I'm sure Carbon has a dedicated method for this operation, but just for fun, I tried to create a function to do the job.
I tested my code with small and large numbers. I know it works with small ones, and it seems OK with large numbers, but I didn't verify.
public function convertTime($sec)
{
$timeParts = [];
foreach ($this->durations() as $tf => $duration) {
extract($this->createTimeString($sec, $tf, $duration));
array_push($timeParts, $timeString);
}
return implode(' ', array_filter($timeParts, function ($item) {
return $item != '';
}));
}
private function durations()
{
return array_reverse([
'second' => 1,
'minute' => $minute = 60,
'hour' => $hour = $minute * 60,
'day' => $day = $hour * 24,
'week' => $day * 7,
'month' => $day * 30,
'year' => $day * 365
]);
}
private function createTimeString($sec, $tf, $duration)
{
$howManyLeft = floor($sec / $duration);
return [
'sec' => !$howManyLeft ? $sec : $sec - $howManyLeft * $duration,
'timeString' => !$howManyLeft ? '' : $howManyLeft . " $tf" . ($howManyLeft > 1 ? 's' : '')
];
}
// convertTime(3684615) returns 1 month 1 week 5 days 15 hours 30 minutes 15 seconds