Skip to content

Instantly share code, notes, and snippets.

@tomgidden
Created January 7, 2015 11:52
Show Gist options
  • Save tomgidden/212ce50c2166398b74ef to your computer and use it in GitHub Desktop.
Save tomgidden/212ce50c2166398b74ef to your computer and use it in GitHub Desktop.
Converts a duration (in seconds) to human readable. A bit crunky, and doesn't work that well.
<?php
function approx_duration($duration, // time period in question, in seconds
$short=false, // single letter suffices (m=month and minute!)
$roundupdown=true, // round up/down rather than just down
$keepdays=false, // largest division is days, not years/months/weeks/days
$keepzeros=true, // keep (and count) zero values
$cutoff=2, // maximum number of fields
$blankzeros=true) // even if $keepzeros for cutoff, eliminate from display
{
if($keepdays)
$periods = array('day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1);
else
$periods = array('year' => 365*86400,
'month' => 30*86400,
'week' => 7*86400,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1);
$buf = array();
$count=0;
foreach($periods as $period=>$unit) {
if($duration<1) break;
$x = $duration / $unit;
$x = $roundupdown ? round($x) : floor($x);
if(($keepzeros and $count>0) or $x or (!$buf and $unit == 1)) {
if($short)
$buf[] = $x.substr($period,0,1);
else
$buf[] = $x.' '.($period.($x!=1?'s':''));
$duration -= $x*$unit;
$count++;
if($count>=$cutoff) break;
}
}
if($blankzeros)
$buf = preg_grep('/^[^0]/', $buf);
return join($short?' ':', ', $buf);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment