将时间量减去相加的时间

时间:2018-09-19 15:15:29

标签: php strtotime background-substraction

我必须在php中将32:30:00(字符串)减去95:05:00(字符串):

95:05:00 - 32:30:00

这是时间的增加。

我找不到任何有效的代码,因为strtotime不接受超过24的值。

请帮助我,谢谢。

例如,我已经尝试过:

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

返回0

它应该返回类似于62:35:00

您知道我是否可以使用moment.js或php lib吗?

3 个答案:

答案 0 :(得分:2)

strtotime不处理持续时间,仅处理有效时间戳。您可以通过将时间戳分解为小时,分钟和秒来分解时间来自己处理。然后,您可以将它们转换为总秒数。

<?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";

然后我们可以将其转换回小时和分钟:

$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

答案 1 :(得分:1)

获得差异秒数的一种方法是使用mktime

$diff = mktime(...explode(':', $time1)) - mktime(...explode(':', $time2));

有多种方法可以转换回所需的字符串格式。我本来建议使用sprintf,但其他答案已经显示出来了,所以我不会打扰。

通常,当您处理时间间隔时,我认为以秒为单位进行所有计算然后在需要输出结果时对其格式进行设置会更容易,因此可以避免执行此类操作。

答案 2 :(得分:0)

这里是另一种选择。

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

function timeDiff($time1, $time2)
{
    $time1 = explode(':', $time1);
    $time2 = explode(':', $time2);

    // Make sure $time2 is always the bigger time
    if ($time1[0] > $time2[0]) {
        $temp = $time1;
        $time1 = $time2;
        $time2 = $temp;
    }

    // Work out the difference in each of the hours, minutes and seconds
    $h = abs($time2[0] - $time1[0]);
    $m = abs($time2[1] - $time1[1]);
    $s = abs($time2[2] - $time1[2]);

    // Ensure that it doesn't say "60", since that is not convention.
    $m = $m == 60 ? 0 : $m;
    $s = $s == 60 ? 0 : $s;

    // If minutes 'overflows', then we need to remedy that
    if ($time2[1] < $time1[1]) {
        $h -= $h == 0 ? $h : 1;
        $m = 60 - $m;
    }

    // Fix for seconds
    if ($time2[2] < $time1[2]) {
        $m -= $m == 0 ? -59 : 1;
        $s = 60 - $s;
    }

    // Zero pad the string to two places.
    $h = substr('00'.$h, -2);
    $m = substr('00'.$m, -2);
    $s = substr('00'.$s, -2);

    return "{$h}:{$m}:{$s}";
}

echo timeDiff($time1, $time2);

我只是简单地分别计算出小时,分钟和秒之间的差异。

我对代码进行了相应的注释,以提供对每个阶段正在发生的情况的更多了解。