83 linhas
2 KiB
PHP
83 linhas
2 KiB
PHP
<?php
|
|
|
|
function ght($ts,$fa=null,$sd=2,$bunit='years',$ozero=false) {
|
|
/*
|
|
$ts is seconds (can be float)
|
|
if not null, $fa has to be an array defining the output suffixes, see below its default ;-)
|
|
$sd is how many decimals to put after a dot after seconds (can be 0)
|
|
$bunit is "from which unit to start counting"
|
|
$ozero is whether to include a zero value for a unit
|
|
*/
|
|
$bunits=['years', 'weeks', 'days', 'hours', 'minutes', 'seconds'];
|
|
$cbunits=count($bunits);
|
|
$obunit=$bunit;
|
|
$bunit=array_search($bunit,$bunits,true);
|
|
if ($bunit===false) {
|
|
fwrite(STDERR,"Function «ght» was called with an unsupported «bunit» value: «{$obunit}».\n");
|
|
$bunit=0;
|
|
}
|
|
$buniti=abs($bunit-$cbunits);
|
|
if ($fa==null) $fa=['year','years','week','weeks','day','days','hour','hours','minute','minutes','second','seconds'];
|
|
$sep=', ';
|
|
$out='';
|
|
$i=0;
|
|
$osep='';
|
|
// years
|
|
if ($buniti>=6) {
|
|
$x=floor($ts/31536000);
|
|
if ($x>0 || $ozero)
|
|
($x==1) ? $out.=$x.' '.$fa[$i] : $out.=$x.' '.$fa[$i+1];
|
|
$ts=$ts-$x*31536000;
|
|
}
|
|
$i+=2;
|
|
// weeks
|
|
if ($buniti>=5) {
|
|
if ($out!='') $osep=$sep;
|
|
$x=floor($ts/604800);
|
|
if ($x>0 || $ozero)
|
|
($x==1) ? $out.=$osep.$x.' '.$fa[$i] : $out.=$osep.$x.' '.$fa[$i+1];
|
|
$ts=$ts-$x*604800;
|
|
}
|
|
$i+=2;
|
|
// days
|
|
if ($buniti>=4) {
|
|
if ($out!='') $osep=$sep;
|
|
$x=floor($ts/86400);
|
|
if ($x>0 || $ozero)
|
|
($x==1) ? $out.=$osep.$x.' '.$fa[$i] : $out.=$osep.$x.' '.$fa[$i+1];
|
|
$ts=$ts-$x*86400;
|
|
}
|
|
$i+=2;
|
|
// hours
|
|
if ($buniti>=3) {
|
|
if ($out!='') $osep=$sep;
|
|
$x=floor($ts/3600);
|
|
if ($x>0 || $ozero)
|
|
($x==1) ? $out.=$osep.$x.' '.$fa[$i] : $out.=$osep.$x.' '.$fa[$i+1];
|
|
$ts=$ts-$x*3600;
|
|
}
|
|
$i+=2;
|
|
// minutes
|
|
if ($buniti>=2) {
|
|
if ($out!='') $osep=$sep;
|
|
$x=floor($ts/60);
|
|
if ($x>0 || $ozero)
|
|
($x==1) ? $out.=$osep.$x.' '.$fa[$i] : $out.=$osep.$x.' '.$fa[$i+1];
|
|
$ts=$ts-$x*60;
|
|
}
|
|
$i+=2;
|
|
// seconds
|
|
if ($buniti>=1) {
|
|
if ($out!='') $osep=$sep;
|
|
$x=round($ts,$sd);
|
|
if ($x>0 || $ozero) {
|
|
if ($sd>0 || $x!=1)
|
|
$out.=$osep.$x.' '.$fa[$i+1];
|
|
elseif ($x==1)
|
|
$out.=$osep.$x.' '.$fa[$i];
|
|
}
|
|
}
|
|
return $out;
|
|
}
|
|
|
|
?>
|