dqtm8504 2018-09-19 07:15
浏览 44
已采纳

将一段时间减去一次

I have to substract 32:30:00 (string) to 95:05:00 (string) in php :

95:05:00 - 32:30:00

THey are coming from an addition of time .

I can't find any code working, cause strtotime doesnt accept more than 24 as a value .

Please help me, thank you.

For example, i ve tried this :

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

It returns 0

It should return something like 62:35:00

Do you know if i can do it with moment.js or a php lib ?

  • 写回答

3条回答 默认 最新

  • duanke1286 2018-09-19 07:35
    关注

    strtotime does not handle durations, only valid timestamps. You can handle it yourself by breaking apart the times by exploding the timestamp into hours, minutes and seconds. You can then convert them into total seconds.

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

    We can then convert it back into hours minutes and 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
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部