1.我的输出格式是290.52262423327秒。如何将其更改为 00:04:51?
- 我想以秒和 HH:MM:SS 格式显示相同的输出,所以如果是秒,我只想显示 290.52 秒。(小数点后只有两个整数)?我怎样才能做到这一点?
我在 php 中工作,输出存在于 $time
变量中。想要将此 $time
更改为 $newtime
,HH:MM:SS 和 $newsec
为 290.52。
谢谢 :)
1.我的输出格式是290.52262423327秒。如何将其更改为 00:04:51?
我在 php 中工作,输出存在于 $time
变量中。想要将此 $time
更改为 $newtime
,HH:MM:SS 和 $newsec
为 290.52。
谢谢 :)
1)
function foo($seconds) {
$t = round($seconds);
return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}
echo foo('290.52262423327'), "n";
echo foo('9290.52262423327'), "n";
echo foo(86400+120+6), "n";
印刷
00:04:51
02:34:51
24:02:06
2)
echo round($time, 2);
编辑:评论指出,如果秒数超过一天(86400秒),则先前的答案会失败。这是一个更新的版本。OP没有指定此要求,因此这可能与OP可能预期的不同,并且在这里可能已经有更好的答案了。我无法忍受这个错误提供了答案。
$iSecondsIn = 290.52262423327;
// Account for days.
$iDaysOut = 0;
while ($iSecondsIn >= 86400) {
$iDaysOut += 1;
$iSecondsIn -= 86400;
}
// Display number of days if appropriate.
if ($iDaysOut > 0) {
print $iDaysOut.' days and ';
}
// Print the final product.
print date('H:i:s', mktime(0, 0, $iSecondsIn));
旧版本,带有错误:
$iSeconds = 290.52262423327;
print date('H:i:s', mktime(0, 0, $iSeconds));
在 23:59:59
小时之前,您可以使用 PHP 默认函数
echo gmdate("H:i:s", 86399);
直到 23:59:59
才会返回结果
如果您的秒数超过 86399,而不是在@VolkerK 回答的帮助下
$time = round($seconds);
echo sprintf('%02d:%02d:%02d', ($time/3600),($time/60%60), $time%60);
将是使用的最佳选择...
我不知道这是否是最有效的方法,但如果您还需要显示天数,这可行:
function foo($seconds) {
$t = round($seconds);
return sprintf('%02d %02d:%02d:%02d', ($t/86400%24), ($t/3600) -(($t/86400%24)*24),($t/60%60), $t%60);
}
试试这个 :)
private function conversionTempsEnHms($tempsEnSecondes)
{
$h = floor($tempsEnSecondes / 3600);
$reste_secondes = $tempsEnSecondes - $h * 3600;
$m = floor($reste_secondes / 60);
$reste_secondes = $reste_secondes - $m * 60;
$s = round($reste_secondes, 3);
$s = number_format($s, 3, '.', '');
$h = str_pad($h, 2, '0', STR_PAD_LEFT);
$m = str_pad($m, 2, '0', STR_PAD_LEFT);
$s = str_pad($s, 6, '0', STR_PAD_LEFT);
$temps = $h . ":" . $m . ":" . $s;
return $temps;
}
就个人而言,我制作了自己的解析器,而不是其他人的答案。适用于天、小时、分钟和秒。并且 should
很容易扩展到数周/数月等。它也适用于 c# 的反序列化
function secondsToTimeInterval($seconds) {
$t = round($seconds);
$days = floor($t/86400);
$day_sec = $days*86400;
$hours = floor( ($t-$day_sec) / (60 * 60) );
$hour_sec = $hours*3600;
$minutes = floor((($t-$day_sec)-$hour_sec)/60);
$min_sec = $minutes*60;
$sec = (($t-$day_sec)-$hour_sec)-$min_sec;
return sprintf('%02d:%02d:%02d:%02d', $days, $hours, $minutes, $sec);
}
基于 https://stackoverflow.com/a/3534705/4342230 ,但增加天数:
function durationToString($seconds) {
$time = round($seconds);
return sprintf(
'%02dD:%02dH:%02dM:%02dS',
$time / 86400,
($time / 3600) % 24,
($time / 60) % 60,
$time % 60
);
}
试试这个