Skip to content
Advertisement

Substract an amount of time to an addition of times

I have to substract 32:30:00 (string) to 95:05:00 (string) in php :

95:05:00 - 32:30:00

THey are coming from an addition of time .

I can’t find any code working, cause strtotime doesnt accept more than 24 as a value .

Please help me, thank you.

For example, i ve tried this :

$time1 = strtotime('32:30:00');
$time2 = strtotime('95:05:00');
$difference = round(abs($time2 - $time1) / 3600,2);
echo 'différence : '.$difference;

It returns 0

It should return something like 62:35:00

Do you know if i can do it with moment.js or a php lib ?

Advertisement

Answer

strtotime does not handle durations, only valid timestamps. You can handle it yourself by breaking apart the times by exploding the timestamp into hours, minutes and seconds. You can then convert them into total seconds.

<?php
$time1 = '95:05:00';
$time2 = '32:30:00';

function timeToSecs($time) {
    list($h, $m, $s) = explode(':', $time);
    $sec = (int) $s;
    $sec += $h * 3600;
    $sec += $m * 60;
    return $sec;
}

$t1 = timeToSecs($time1);
$t2 = timeToSecs($time2);
$tdiff = $t1 - $t2;

echo "Difference: $tdiff seconds";

We can then convert it back into hours minutes and seconds:

$start = new DateTime("@0");
$end   = new DateTime("@$tdiff");

$interval = $end->diff($start);

$time = sprintf(
    '%d:%02d:%02d',
    ($interval->d * 24) + $interval->h,
    $interval->i,
    $interval->s
);

echo $time; // 62:35:00
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement