dsnpjz6907 2019-04-29 12:47

# 如何计算负/正时间且大于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);
}

\$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 速度位置规划实现精确定位的问题