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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵