我的问题是,如何使用PHP我们可以拥有一个自动化系统,它可以做到这一点:
如果我们有$seconds= 120;
并且脚本应该获得此值,请看这等于2分钟,然后在分钟中打印此值。与我们希望持续数天相同,我们可以说$days = 7;
脚本需要获取此值,检查天数,在这种情况下需要打印 1周。谢谢你们!
答案 0 :(得分:8)
<?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)
答案 1 :(得分:5)
4周(s)6天(s)53小时(s)20分钟
53小时? 另外,300000秒是3天11小时,而不是3天23小时
function formatSeconds($secs) {
if (!$secs = (int)$secs)
return '0 seconds';
$units = array(
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1
);
$strs = array();
foreach($units as $name=>$int){
if($secs < $int)
continue;
$num = (int) ($secs / $int);
$secs = $secs % $int;
$strs[] = "$num $name".(($num == 1) ? '' : 's');
}
return implode(', ', $strs);
}
var_dump(formatSeconds(0));
var_dump(formatSeconds(30));
var_dump(formatSeconds(300));
var_dump(formatSeconds(3000));
var_dump(formatSeconds(30000));
var_dump(formatSeconds(300000));
var_dump(formatSeconds(3000000));
var_dump(formatSeconds(30000000));
string(9) "0 seconds"
string(10) "30 seconds"
string(9) "5 minutes"
string(10) "50 minutes"
string(19) "8 hours, 20 minutes"
string(28) "3 days, 11 hours, 20 minutes"
string(37) "4 weeks, 6 days, 17 hours, 20 minutes"
string(37) "49 weeks, 4 days, 5 hours, 20 minutes"
答案 2 :(得分:1)
你可以使用简单的东西:
$seconds = 120;
$minutes = floor($seconds/60);
echo $minutes.' min';
我不确定我是否已正确理解你的问题。