dsnpjz6907 2019-04-29 12:47
浏览 48
已采纳

如何计算负/正时间且大于24:00?

I have to make a calculation with times like these that come from an array:

+04:43
03:33
-10:33

I tried using Datetime and stuff but the class just broke when it surpassed 24:00 time (10:00 + 20:00 for example). So I tried something like this:

I transformed all my hh:mm to seconds with explode:

foreach($stringSaldo as $saldo) {
          $horaM[] =  explode(':',$saldo);
      }
      $totalHora = 0;
      $totalMin = 0;
      foreach($horaM as $hora) {
          $totalHora = ($totalHora + $hora[0]);
          $totalMin =( $totalMin + $hora[1]);
      }
      $totalHora = $totalHora * 3600;
      $totalMin = $totalMin * 60;
      $totalSeconds = $totalHora + $totalMin;

Then I tried to make that seconds in time:

$hours = floor($totalSeconds / 3600);
      $minutes = floor(($totalSeconds / 60) % 60);
      $seconds = $totalSeconds % 60;
 echo $hours. ":" . $minutes;

For some reason when I have times like: -03:34 and +01:00 the calculation fails, it gives -02:-26 but it should be -02:34.

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • donglin317704291 2019-04-29 14:37
    关注

    I think I have this ironed out. It is important that you do the arithmetic with the absolute values and separately handle the sign. I have included some zero padding to ensure that you are getting a consistent string result. My regular expression makes the + or - optional.

    Code: (Demo of your 3 test cases)

    function timeToSeconds($time) {
        if (!preg_match('~([+-]?)(\d{2}):(\d{2})~', $time, $out)) {
            echo "failed to parse $time
    ";
            return 0;
        } else {
            return (($out[2] * 3600) + $out[3] * 60) * ($out[1] == '-' ? -1 : 1);
        }
    }
    function secondsToTime($seconds) {
        $sign = $seconds < 0 ? '-' : '';
        $abs = abs($seconds);
        return $sign . str_pad(floor($abs / 3600), 2, '0', STR_PAD_LEFT) . ':' . str_pad(floor($abs / 60 % 60), 2, '0', STR_PAD_LEFT);
    }
    
    $times = ['-03:34', '+01:00'];
    $seconds = 0;
    foreach ($times as $time) {
        $seconds += timeToSeconds($time);
    }
    echo $seconds;  // -9240
    echo "
    ---
    ";
    echo secondsToTime($seconds);  // -02:34
    

    Relevant resource: https://stackoverflow.com/a/3856312/2943403

    p.s. When you split time on :, the hours may be positive or negative, but the minutes will always be positive. This is a fundamental issue with your posted snippet.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)