gpt4 book ai didi

php - 几秒到几分钟,几天到几周

转载 作者:可可西里 更新时间:2023-10-31 23:57:39 26 4
gpt4 key购买 nike

我的问题是,我们如何使用 PHP 拥有一个自动化系统,它可以执行以下操作: 如果我们有 $seconds= 120;脚本应该得到这个值,看到它等于 2 分钟,然后在 分钟 后打印这个值。就像我们想要几天一样,让我们​​说 $days = 7;脚本需要获取此值,检查天数,在本例中它需要打印 1 周。谢谢大家!

最佳答案

<?php

/**
* @param int $secs
*
* @return string
*/
function formatSeconds($secs) {
$secs = (int)$secs;
if ( $secs === 0 ) {
return '0 secs';
}
// variables for holding values
$mins = 0;
$hours = 0;
$days = 0;
$weeks = 0;
// calculations
if ( $secs >= 60 ) {
$mins = (int)($secs / 60);
$secs = $secs % 60;
}
if ( $mins >= 60 ) {
$hours = (int)($mins / 60);
$mins = $mins % 60;
}
if ( $hours >= 24 ) {
$days = (int)($hours / 24);
$hours = $hours % 60;
}
if ( $days >= 7 ) {
$weeks = (int)($days / 7);
$days = $days % 7;
}
// format result
$result = '';
if ( $weeks ) {
$result .= "{$weeks} week(s) ";
}
if ( $days ) {
$result .= "{$days} day(s) ";
}
if ( $hours ) {
$result .= "{$hours} hour(s) ";
}
if ( $mins ) {
$result .= "{$mins} min(s) ";
}
if ( $secs ) {
$result .= "{$secs} sec(s) ";
}
$result = rtrim($result);
return $result;
}

echo formatSeconds(0), "\n";
echo formatSeconds(30), "\n";
echo formatSeconds(300), "\n";
echo formatSeconds(3000), "\n";
echo formatSeconds(30000), "\n";
echo formatSeconds(300000), "\n";
echo formatSeconds(3000000), "\n";
echo formatSeconds(30000000), "\n";

输出:

0 secs
30 sec(s)
5 min(s)
50 min(s)
8 hour(s) 20 min(s)
3 day(s) 23 hour(s) 20 min(s)
4 week(s) 6 day(s) 53 hour(s) 20 min(s)
49 week(s) 4 day(s) 53 hour(s) 20 min(s)

关于php - 几秒到几分钟,几天到几周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5088109/

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