本文介绍了PHP:时差(min:sec:十分之一)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 minutes:seconds.tenth 进行操作时,如何计算时差?
例如,如何实现此示例: 40:24.5-67:52.4 = -27:27.9

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

推荐答案

就像您已经尝试过"一样,您可以使用 DateTime 扩展名:

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

使用示例:

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

这篇关于PHP:时差(min:sec:十分之一)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 09:46