Search code examples
phpdatedatetimetimedate-arithmetic

PHP: Time difference (min:sec:tenths)


How can I calculate time difference when operating with minutes:seconds.tenth ?
For example how can I achieve this example: 40:24.5 - 67:52.4 = -27:27.9

I was going to use this but then discovered lack of tenths:

$time1 = new date('40:24.5');
$time2 = new date('67:52.4');
$interval = $time1->diff($time2);
echo $interval->format('%R%%i:%s:??');

Solution

  • Like you already "tried", you can use DateTime extension:

    function time_difference($t1, $t2) {
        $t1 = DateTime::createFromFormat('i:s.u', $t1, new DateTimezone('UTC'));
        $t2 = DateTime::createFromFormat('i:s.u', $t2, new DateTimezone('UTC'));
        $diff = $t2->diff($t1);
        $u = $t2->format('u') - $t1->format('u');
    
        if ($u < 0) {
            $diff = $t2->modify('-1 second')->diff($t1);
            $u = 1000000 - abs($u);
        }
    
        $u = rtrim(sprintf('%06d', $u), '0') ?: '0';
        return $diff->format('%R%I:%S.') . $u;
    }
    

    Use example:

    echo time_difference('40:24.5', '67:52.4');
    # -27:27.9
    

    demo