Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP time string format to number of hours as integer

Tags:

php

time

format

I'm getting aggregate values of time passed from DB in formats such as

 "84:00:00"
 "14:30:00"
 "20:00:00"
 "02:00:00"
"120:00:00"

and I need to convert that to integer values as follows:

 84
 14.5
 20
  2
120

is there any way to achieve this (rather simply); to my understanding strtotime() returns false if the value is greater than 24:00:00

like image 918
toddddos Avatar asked Oct 16 '25 17:10

toddddos


2 Answers

Solution (thanks to @deceze):

if($time != '0') {
    list($hours, $minutes) = explode(':', $time);
    return $hours + ($minutes / 60);
}
return 0;
like image 54
toddddos Avatar answered Oct 18 '25 10:10

toddddos


You could use the function TimeToSec() and then just devide seconds with 3600, and you will receive number of hours.

function TimeToSec($time) {
    $sec = 0;
    foreach (array_reverse(explode(':', $time)) as $k => $v) $sec += pow(60, $k) * $v;
    return $sec;
}

echo TimeToSec('14:30:00') / 3600;

demo

like image 31
Glavić Avatar answered Oct 18 '25 12:10

Glavić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!