Claudio
Claudio

Reputation: 1234

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:05 -> 34  
48:40:30 -> 49

Any ideas?

Regards Claudio

Upvotes: 2

Views: 5640

Answers (4)

Mark Grey
Mark Grey

Reputation: 10257

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

Upvotes: 2

Chris Baker
Chris Baker

Reputation: 50592

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

Upvotes: 3

Tim
Tim

Reputation: 14154

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

Upvotes: 0

Marc B
Marc B

Reputation: 360602

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

Upvotes: 3

Related Questions