经过几次尝试后,我未能获得正确的结果。情况是这样的:
$morning = '01:05:12';
$evening = '14:05:29';
$sum = gmdate('H:i:s', strtotime($morning) + strtotime($evening));
echo $sum;
它不工作,sum变量输出06:42:25,这当然不正确。我该如何解决这个问题?
谢谢
function strToDuration($str) {
sscanf($str, '%d:%d:%d', $hours, $minutes, $seconds);
return $seconds + ($minutes * 60) + ($hours * 60 * 60);
}
function durationToStr($duration) {
$hours = floor($duration / (60 * 60));
$seconds = $duration % (60 * 60);
$minutes = floor($seconds / 60);
$seconds %= 60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
$morning = '01:05:12';
$evening = '14:05:29';
echo durationToStr(strToDuration($morning) + strToDuration($evening));
首先从时间中减去strtotime("00:00:00")
。然后把它们加起来,格式化。
$morning = '01:05:12';
$evening = '14:05:29';
$sum = gmdate('H:i:s', (strtotime("01:05:12")-strtotime("00:00:00"))+(strtotime("14:05:29")-strtotime("00:00:00")));
echo $sum;
您的时区设置是什么(date_default_timezone_get()
) ?strtotime()在生成时间戳时假设当前时区(如果没有指定),而gmdate()输出UTC时间。
Upd:另外,请参阅关于持续时间的注释-来自strtotime的时间戳将被扩展为"01:05:12 of %current date%",因此它们的总和将不仅仅是"new time of %current date%"。
计算时间的简单示例:
$morning = '01:05:12';
$evening = '14:05:29';
$morning = strtotime("1970-01-01 $morning UTC"); # convert time to seconds
$evening = strtotime("1970-01-01 $evening UTC"); # same as above
$seconds = $morning + $evening; # sum seconds
$hours = floor($seconds / 3600); $seconds %= 3600; # calculate number of hours
$minutes = floor($seconds / 60); $seconds %= 60; # calculate number of minutes
echo sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds); # 15:10:41
演示可以使用PHP的DateInterval函数!
function getTotalTime($times)
{
$h = $m = $s = 0;
foreach ($times as $time) {
$time = new DateTime($time);
$h += $time->format('H');
$m += $time->format('i');
$s += $time->format('s');
}
$interval = new DateInterval("PT{$h}H{$m}M{$s}S");
return $interval->format('%H:%I:%S');
}
$morning = '01:05:12';
$evening = '14:05:29';
echo getTotalTime([$morning, $evening]);