在PHP中使用时间值聚合两个字符串

时间:2014-03-13 10:19:06

标签: php date time aggregate-functions strtotime

经过几次尝试后,我找不到合适的结果。情况如下:

$morning = '01:05:12';
$evening = '14:05:29';

$sum = gmdate('H:i:s', strtotime($morning) + strtotime($evening));
echo $sum;

它不起作用,求和变量输出06:42:25,如果当然不正确的话。我该如何解决这个问题?

谢谢

5 个答案:

答案 0 :(得分:1)

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));

答案 1 :(得分:0)

您的时区设置是什么(date_default_timezone_get())? strtotime()在生成时间戳时假定当前时区(如果没有指定),而gmdate()则输出UTC时间。

更新:此外,请参阅有关持续时间的评论 - 来自strtotime的时间戳将扩展为“当前日期%的01:05:12”,因此它们的总和不仅仅是“当前日期%%的新时间”

答案 2 :(得分:0)

首先从时间中减去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;

答案 3 :(得分:0)

求和时间的简单示例:

$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

demo

答案 4 :(得分:0)

您可以使用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]);