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

时间:2017-07-03 05:57:27

标签: php string time units-of-measurement elapsedtime

我的字符串函数时间戳

// 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小时15分钟

期望输出

  • 1秒
  • 1分钟 1秒
  • 1小时,1分钟 1秒
  • 1天,1小时,1分钟 1秒

2 个答案:

答案 0 :(得分:3)

我已经做了一次这样的功能,所以我可以将它重用于更多的应用程序:

function smart_implode($values, $join, $joinLast) {
    $lastValue = end($values); // take last value
    unset($arr[count($values)-1]); // remove from array
    $values = implode($join, $values); // implode all remaining values
    return $values.$joinLast.$lastValue; // and add the last value
}

echo smartImplode($timeValueArray, ", ", " and ");

这有额外的好处,如果你不想显示0值(如 0分钟),你就不会坚持使用硬编码的解决方案。只是不要在smart_implode()

中输入它
5 hours, 0 mins and 7 seconds -> 5 hours and 7 seconds 

Quick example for your specific code.

答案 1 :(得分:3)

我完全改变了我的第一篇文章。我想摆脱所有的数学处理,所以我决定使用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