Question

after few tries I have failed getting the right result. Situation looks like this:

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

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

It doen't work, sum variable outputs 06:42:25, which if of course not correct. How should I fix this?

Thank you

Was it helpful?

Solution

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

OTHER TIPS

First subtract strtotime("00:00:00") from the time. Then add them up and format it.

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

What is your timezone setting (date_default_timezone_get()) ? strtotime() assumes current time zone (if not any specified) when generating timestamps, while gmdate() outputs UTC time.

Upd: also, see comment about durations - timestamps from strtotime will be expanded like "01:05:12 of %current date%", so sum of them won't be just "new time of %current date%".

Simple example of summing times:

$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

You can use PHP's DateInterval function!

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]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top