繁体   English   中英

将时间量减去相加的时间

[英]Substract an amount of time to an addition of times

我必须在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吗?

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

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

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

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

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

这是另一种选择。

$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);

我只是分别算出每个小时,分钟和秒之间的差异。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM