dongtuanzi1080 2014-03-24 19:16
浏览 27
已采纳

php添加和减去时间

Im attempting to code a little script that will work out hours.

I would like a travel time, start time and a finish time. The problem I'm having is getting the total time.

$travel = $_POST['travel'];  // -- 1.00 (1 hour)
$start = $_POST['start'];    // -- 7.30 
$finish = $_POST['finish'];  // -- 16.00 

so the total time would be ( 16.00 - 7.30 ) + 1.00 = 9.5 hours

But this doesn't work because 16.00 - 7.30 = 8.7, then plus the 1 = 9.7.

I understand why its wrong, but not how to fix it. I cant change the time values to .50 for the half hour because the value is coming from a jquery plugin. Any help would be much appreciated.

// update

$a = new DateTime($_POST['start']);
$b = new DateTime($_POST['finish']);
$interval = $a->diff($b);

echo $interval->format("%H");

This works great, the only thing is how do I display hours and minutes e.g '9.00'

  • 写回答

2条回答 默认 最新

  • duandang6352 2014-03-24 19:20
    关注

    update

    Since you changed your question... Looking at the syntax for DateTime::format(),

    echo $interval->format("H.i");
    

    should give you the formatting you want.

    old answer

    The easiest way to deal with time is by representing each time as a number of seconds. (If it's a date, use the number of seconds since the epoch.) You can write some helper functions to convert your times to/from the formats that you want.

    For example,

    16.00 -> 57600  
    7.30 -> 27000  
    1.00 -> 3600
    
    (57600 - 27000) + 3600 = 34200  
    34200 -> 9.30
    

    here are the helper functions I came up with:

    function timeToSeconds ($time) {
        $hours = floor($time);
        $minutes = ($time - $hours) * 100;
        $seconds = ($hours * 3600) +  ($minutes * 60);
        return $seconds;
    }
    
    function secondsToTime ($seconds) {
        $hours = floor($seconds / 3600);
        $minutes = ($seconds - ($hours * 3600)) / 60;
        $time = "" . $hours . "." . $minutes;
        return $time;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line