output:
36 years 8 months 3 weeks 2 days 24 minutes 32 seconds
36 years 8 months 3 weeks 2 days
36 years 8 months
<?php
function duration($seconds, $max_periods) {
$periods = array('year' => 31536000, 'month' => 2419200, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1);
$i = 1;
foreach ( $periods as $period => $period_seconds ) {
$period_duration = floor($seconds / $period_seconds);
$seconds = $seconds % $period_seconds;
if ( $period_duration == 0 ) continue;
$duration[] = $period_duration .' '. $period . ($period_duration > 1 ? 's' : '');
$i++;
if ( $i > $max_periods ) break;
}
if (is_null($duration)) return 'just now';
return implode(' ', $duration);
}
?>
I also wanted to note that the function fails if the process completes in less than 1 second, as @Dean O also pointed out. I've added:
if (is_null($duration))
$duration = array('less than 1 second');
before the return statement to handle this case.
IMO, this is a better alternative to what @Dean O suggests since it results in correct output under all use cases.
Should put $duration = array() at the top. Initializing duration will output an empty string when $period is 0 or you otherwise get an error. Useful in situations where you calculate the duration of something that may not have started yet and makes it a bit more solid and stable overall by covering this edge case.
Basically this will transform seconds in human readable durations. The first parameter of the function represents the number of seconds to transform, while the second represents how detailed will the transformation be (in his examples, duration 6 returns years, months, weeks, days, minutes and seconds, while duration 4 returns only years, months, weeks and days).
the biggest value $max_periods should have is 7 (years, months, weeks, days, hours, minutes and seconds), but in some cases, the function will act as with $max_periods = 6 (when one of the time values is null).
I would vote this as a very useful snippet. good job