PHP: Time difference (min:sec:tenths)

霸气de小男生 提交于 2021-01-27 18:00:32

问题


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:??');

回答1:


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



来源:https://stackoverflow.com/questions/21044088/php-time-difference-minsectenths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!