gpt4 book ai didi

php - 如何根据需要将秒数转换为具有更大单位的纯英文字符串?

转载 作者:可可西里 更新时间:2023-11-01 00:29:16 26 4
gpt4 key购买 nike

我的时间戳转字符串函数

// 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

关于php - 如何根据需要将秒数转换为具有更大单位的纯英文字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44878642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com