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 将安全信息用到以下对象时发生以下错误:c:dumpstack.log.tmp 另一个程序正在使用此文件,因此无法访问
  • ¥15 速度位置规划实现精确定位的问题
  • ¥15 代码问题:df = pd.read_excel('c:\User\18343\Desktop\wpsdata.xlxs')路径读不到
  • ¥15 为什么视频算法现在全是动作识别?
  • ¥15 编写一段matlab代码
  • ¥15 用Python做岩石类别鉴定软件
  • ¥15 关于调取、提交更新数据库记录的问题
  • ¥15 之前删了盘从下vs2022遇见这个问题 搞了一整天了
  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示