1

我需要四舍五入。我想知道如何将时间舍入到下一个小时并将其用作 PHP 中的 int。

前任:

24:00:02 -> 25  
33:15:05 -> 34  
48:40:30 -> 49

有任何想法吗?

问候克劳迪奥

4

4 回答 4

3

你想要像DateTime::setTime这样的东西。使用日期函数提取小时/分钟/秒,确定小时是否需要增加,然后将小时设置为适当的值并将分钟和秒归零。

唔。再次阅读您的问题时,如下所示:

$sec = date('s', $timevalue);
$min = date('i', $timevalue);
$hour = date('G', $timevalue);

if (($sec > 0) or ($min > 0)) { $hour++; } // if at x:00:01 or better, "round up" the hour
于 2011-02-15T18:38:41.290 回答
3

我假设您使用的格式是 HOURS:MINUTES:SECONDS,表示持续时间而不是一天中的某个时间,并且我假设您将此值作为字符串获取。在这种情况下,您的解决方案是自制功能,因为这是一个非常具体的情况。像这样的东西:

function roundDurationUp($duration_string='') {
     $parts = explode(':', $duration_string);
     // only deal with valid duration strings
     if (count($parts) != 3)
       return 0;

     // round the seconds up to minutes
     if ($parts[2] > 30)
       $parts[1]++;

     // round the minutes up to hours
     if ($parts[1] > 30)
       $parts[0]++;

     return $parts[0];
    }

print roundDurationUp('24:00:02'); // prints 25
print roundDurationUp('33:15:05'); // prints 34
print roundDurationUp('48:40:30'); // prints 49

试试看:http ://codepad.org/nU9tLJGQ

于 2011-02-15T19:01:47.390 回答
2
function ReformatHourTime($time_str){
                $min_secs = substr($time_str,3);
                $direction = round($min_secs/60);

                if($dir == 1){
                    return $time_str+1;
                }else{
                    return floor($time_str);
                }
         }
于 2011-02-15T19:07:32.873 回答
0

如果您像处理数字一样处理时间字符串,PHP 会将其视为一个并删除除第一个数字之外的所有内容。

print '48:40:30' + 1; # 49
print '30:00:00' + 1; # 31
于 2011-02-15T18:39:53.053 回答