开发者

PHP round time and hours

I need to round some times. I would like to know how I can round a time to the next hour and use that as an int in PHP.

Ex:

24:00:02 -> 25  
33:15:开发者_如何学JAVA05 -> 34  
48:40:30 -> 49

Any ideas?

Regards Claudio


You'd want something like DateTime::setTime. Use the date functions to extract the hours/minutes/seconds, figure out if the hour needs to be incremented, then set the hour to the appropriate value and zero out the minutes and seconds.

hmm. on reading your question again, something like this:

$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


I am assuming the format you're using is HOURS:MINUTES:SECONDS, expressing a duration of time rather than a time of day, and I'll assume that you've got this value as a string. In which case, your solution is a home-brew function, as this is a pretty specific case. Something like this:

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

Try it: http://codepad.org/nU9tLJGQ


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);
                }
         }


If you handle the time string like a number, PHP treats it like one and removes everyting but the first digits.

print '48:40:30' + 1; # 49
print '30:00:00' + 1; # 31
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜