1

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?

Community
  • 1
  • 1

1 Answers1

0

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\n";
        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 "\n---\n";
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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • u saved my life, ty very much, worked as it should now! i lost 10 hours trying to figured what i was doing lol. – Victor barbieri Apr 29 '19 at 20:43
  • You have revived my shriveling belief that it is possible for a new user to post a complete, clear, and verifiable question with a coding attempt. Good on you. Please always great questions like this. – mickmackusa Apr 29 '19 at 22:40