编程语言
首页 > 编程语言> > php – 如何根据需要将秒数转换为带有更大单位的普通英语字符串?

php – 如何根据需要将秒数转换为带有更大单位的普通英语字符串?

作者:互联网

我的字符串函数时间戳

// Timestamp To String
function time2string($time) {

    // DAYS
    $d = floor($time/86400);
    if ($d > 0) { $_d = $d.($d > 1 ? ' days' : ' day'); }
    else { $_d = ""; }

    // HOURS
    $h = floor(($time-$d*86400)/3600);
    if ($h > 0) { $_h = $h.($h > 1 ? ' hours' : ' hour'); }
    else { $_h = ""; }

    // MINUTES
    $m = floor(($time-($d*86400+$h*3600))/60);
    if ($m > 0) { $_m = $m.($m > 1 ? ' minutes' : ' minute'); }
    else { $_m = ""; }

    // SECONDS
    $s = $time-($d*86400+$h*3600+$m*60);
    if ($s >0) { $_s = $s.($s > 1 ? ' seconds' : ' second'); }
    else { $s = ""; }

    $time_str = $_d.' '.$_h.' '.$_m.' '.$_s;
    return $time_str;
}

现场演示:https://eval.in/826278

用法

time2string(22500)

6 hours 15 minutes

期望的输出

> 1秒
> 1分1秒
> 1小时,1分钟和1秒
> 1天,1小时,1分钟和1秒

解决方法:

我完全改变了第一篇文章.我想摆脱所有的数学处理,所以我决定使用DateTime对象……毕竟diff()非常适合这个任务.

代码:(Demo)

function time2string($time) {
    if($time==0){return '0 seconds';}
    $t1=new DateTime();
    $t2=new DateTime("+$time seconds");
    $diff=$t1->diff($t2);
    $units=['days'=>'day','h'=>'hour','i'=>'minute','s'=>'second'];  // nominate units
    foreach($units as $k=>$v){
        if($diff->$k!=0){$result[]=$diff->$k.' '.$v.($diff->$k>1?'s':'');}  // store non-zero strings
    }
    if(sizeof($result)==1){
        return $result[0];  // return single element
    }else{
        $last=array_splice($result,-1);  // remove last element from $a and store separately
        return implode(', ',$result)." and {$last[0]}";  // return with correct delimiters
    }
}

echo time2string(122510); // output: 1 day, 10 hours, 1 minute and 50 seconds

echo time2string(0); // output: 0 seconds

echo time2string(1); // output: 1 second

echo time2string(9199800); // output: 106 days, 11 hours and 30 minutes

echo time2string(69206400); // output: 801 days

echo time2string(3599); // output: 59 minutes and 59 seconds

标签:units-of-measurement,php,string,time,elapsedtime
来源: https://codeday.me/bug/20190823/1699833.html