我需要将秒转换为“小时:分钟:秒”。
例如:“685”转换为“00:11:25”
我怎样才能做到这一点呢?
我需要将秒转换为“小时:分钟:秒”。
例如:“685”转换为“00:11:25”
我怎样才能做到这一点呢?
当前回答
其他解决方案使用gmdate,但在超过86400秒的边缘情况下会失败。为了解决这个问题,我们可以自己简单地计算小时数,然后让gmdate将剩余的秒计算为分/秒。
echo floor($seconds / 3600) . gmdate(":i:s", $seconds % 3600);
输入:6030 输出:1:40:30
输入:2000006030 输出:555557:13:50
其他回答
不知道为什么还没有提出这个建议,但是这里有一个使用DateInterval的变体,它的优点是秒> 86400不是问题(只是不要期望小时< 24)
noteable:该函数返回DateInterval对象,因此输出格式由调用者决定
function seconds2interval($seconds) {
$s = intval($seconds);
$hrs = floor($s / 3600);
$min = floor(($s - ($hrs * 3600)) / 60);
$sec = $s % 60;
$duration = sprintf('PT%dH%dM%dS', $hrs, $min, $sec);
$d = new DateInterval($duration);
return $d;
}
$d = seconds2interval(93837.3113);
echo $d->format('%H:%I:%s'); // 26:03:57
// TEST
// 1 Day 6 Hours 50 Minutes 31 Seconds ~ 111031 seconds
$time = 111031; // time duration in seconds
$days = floor($time / (60 * 60 * 24));
$time -= $days * (60 * 60 * 24);
$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);
$minutes = floor($time / 60);
$time -= $minutes * 60;
$seconds = floor($time);
$time -= $seconds;
echo "{$days}d {$hours}h {$minutes}m {$seconds}s"; // 1d 6h 50m 31s
给你
function format_time($t,$f=':') // t = seconds, f = separator
{
return sprintf("%02d%s%02d%s%02d", floor($t/3600), $f, ($t/60)%60, $f, $t%60);
}
echo format_time(685); // 00:11:25
仅当秒数小于86400(1天)时使用函数gmdate():
$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05
参见: gmdate()
运行Demo
将秒转换为“脚”格式无限制*:
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05
参见:floor(), sprintf(),算术运算符
运行Demo
DateTime扩展的示例使用:
$seconds = 8525;
$zero = new DateTime("@0");
$offset = new DateTime("@$seconds");
$diff = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05
参见:DateTime::__construct(), DateTime::modify(), clone, sprintf ()
运行Demo
MySQL示例的结果范围被限制为TIME数据类型,从-838:59:59到838:59:59:
SELECT SEC_TO_TIME(8525);
# 02:22:05
看:SEC_TO_TIME
运行Demo
PostgreSQL的例子:
SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05
运行Demo
任何人在未来寻找这个,这给了最初的海报要求的格式。
$init = 685;
$hours = floor($init / 3600);
$hrlength=strlen($hours);
if ($hrlength==1) {$hrs="0".$hours;}
else {$hrs=$hours;}
$minutes = floor(($init / 60) % 60);
$minlength=strlen($minutes);
if ($minlength==1) {$mins="0".$minutes;}
else {$mins=$minutes;}
$seconds = $init % 60;
$seclength=strlen($seconds);
if ($seclength==1) {$secs="0".$seconds;}
else {$secs=$seconds;}
echo "$hrs:$mins:$secs";