string convertsecs(int seconds [,bool human [, string format]]) -- Convert a number of seconds to a human readable format.
<?php |
This will output:
100000 seconds is 01d 03:46:40 or 1 day 3 hours 46 minutes 40 seconds |
Published under the terms of the BSD License
<?php
function convertsecs($seconds, $human = false, $format = false) {
if(!defined('SECOND')) { define('SECOND', 1); }
if(!defined('MINUTE')) { define('MINUTE', 60*SECOND); }
if(!defined('HOUR')) { define('HOUR', 60*MINUTE); }
if(!defined('DAY')) { define('DAY', 24*HOUR); }
if(!defined('YEAR')) { define('YEAR', 365*DAY); }
$suf_d=$suf_h=$suf_m=$suf_s='';
if ($seconds < MINUTE) {
if ($human === true && $format === false) {
if ($seconds != 1) { $s = 's'; }
$format = "%d second$s";
}
elseif ($format === false) {
$format = "00:%02d";
}
return sprintf($format, $seconds);
}
elseif ($seconds < HOUR) {
$m = floor($seconds / MINUTE);
$s = $seconds % MINUTE;
if ($human === true && $format === false) {
if ($m != 1) { $suf_m = 's'; }
if ($s != 1) { $suf_s = 's'; }
$format = "%d minute$suf_m %d second$suf_s";
}
elseif ($format === false) {
$format = "%02d:%02d";
}
return sprintf($format, $m, $s);
}
elseif ($seconds < DAY) {
$h = floor($seconds / HOUR);
$m = floor(($seconds - $h*HOUR) / MINUTE);
$s = $seconds % MINUTE;
if ($human === true && $format === false) {
if ($h != 1) { $suf_h = 's'; }
if ($m != 1) { $suf_m = 's'; }
if ($s != 1) { $suf_s = 's'; }
$format = "%d hour$suf_h %d minute$suf_m %d second$suf_s";
}
elseif ($format === false) {
$format = "%02d:%02d:%02d";
}
return sprintf($format, $h, $m, $s);
}
elseif ($seconds < YEAR) {
$d = floor($seconds / DAY);
$h = floor(($seconds - $d*DAY) / HOUR);
$m = floor(($seconds - $d*DAY - $h*HOUR) / MINUTE);
$s = floor($seconds - $d*DAY - $h*HOUR - $m*MINUTE);
if ($human === true && $format === false) {
if ($d != 1) { $suf_d = 's'; }
if ($h != 1) { $suf_h = 's'; }
if ($m != 1) { $suf_m = 's'; }
if ($s != 1) { $suf_s = 's'; }
$format = "%d day$suf_d %d hour$suf_h %d minute$suf_m %d second$suf_s";
}
elseif ($format === false) {
$format = "%02dd %02d:%02d:%02d";
}
return sprintf($format, $d, $h, $m, $s);
}
else {
$y = floor($seconds / YEAR);
$d = floor(($seconds - $y*YEAR) / DAY);
$h = floor(($seconds - $y*YEAR - $d*DAY) / HOUR);
$m = floor(($seconds - $y*YEAR - $d*DAY - $h*HOUR) / MINUTE);
$s = floor($seconds - $y*YEAR - $d*DAY - $h*HOUR - $m*MINUTE);
if ($human === true && $format === false) {
if ($y != 1) { $suf_y = 's'; }
if ($d != 1) { $suf_d = 's'; }
if ($h != 1) { $suf_h = 's'; }
if ($m != 1) { $suf_m = 's'; }
if ($s != 1) { $suf_s = 's'; }
$format = "%d year$suf_y %d day$suf_d %d hour$suf_h %d minute$suf_m %d second$suf_s";
}
elseif ($format === false) {
$format = "%02dy %02dd %02d:%02d:%02d";
}
return sprintf($format, $y, $d, $h, $m, $s);
}
}
?>
Last updated: Sat Jun 14 20:02:45 CEST 2008