Last active
February 28, 2022 08:48
-
-
Save sfaut/04bce3072aabe64dea0bae6283b6dcfe to your computer and use it in GitHub Desktop.
Converts seconds to human reading duration like "4 days, 13 hours, 5 minutes, 49 seconds"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function human_duration(int $seconds): string | |
{ | |
if ($seconds < 0) { | |
return 'invalid'; | |
} | |
if ($seconds === 0) { | |
return 'now'; | |
} | |
// Units | |
$minute = 60; | |
$hour = $minute * 60; | |
$day = $hour * 24; | |
$year = $day * 365; | |
$parts = [ // Singular units, to easily add "s" when needed | |
'year' => (int)floor($seconds / $year), // floor() returns float | |
'day' => (int)floor($seconds % $year / $day), | |
'hour' => (int)floor($seconds % $day / $hour), | |
'minute' => (int)floor($seconds % $hour / $minute), | |
'second' => $seconds % 60, | |
]; | |
// Keep significant parts | |
$parts = array_filter($parts, fn ($value) => $value !== 0); | |
// Build labels | |
foreach ($parts as $unit => $value) { | |
$parts[$unit] = $value . ' ' . $unit . ($value >= 2 ? 's' : ''); | |
} | |
$result = implode(', ', $parts); | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment