Reputation: 29
I wrote code to convert the float value of time and convert it into hours and minutes. If input 2.5 it will return 2:30 (2 hours and 30 minutes).
$input = '2:5';
$num_hours=str_replace(":",".",$input,$num_hours) ;
$hours = floor($num_hours);
$mins = round(($num_hours - $hours) * 60);
echo $hour_one = $hours.'.'.$mins;
but now I want to reverse it: if input 2:30
it should return 2.5
.
Upvotes: 1
Views: 6558
Reputation: 157967
You can use the modulo %
operator for the first operation:
$value = 2.5;
echo floor($value) . ':' . (($value * 60) % 60);
Output:
2:30
To convert them back you can use:
$value = "2:30";
$parts = explode(':', $value);
echo $parts[0] + floor(($parts[1]/60)*100) / 100 . PHP_EOL;
2.5
AS a function we can use :
function hours_tofloat($val){
if (empty($val)) {
return 0;
}
$parts = explode(':', $val);
return $parts[0] + floor(($parts[1]/60)*100) / 100;
}
Upvotes: 5
Reputation: 109
function getPartialTime($sTime)
{
$aTime = explode(':', $sTime);
if (isset($aTime[1]) {
$iPart = round($aTime[1]*100/60);
} else {
$iPart = 0;
}
return $aTime[0].'.'.$iPart;
}
This will return on getPartialTime('2:30') => 2.5
Upvotes: 0
Reputation: 1559
i think this is your answer try this
<?php
$str = str_replace(":", ".", "2:5");
$float_value = floatval($str); // this Line Convertit une chaîne en nombre à virgule flottante
echo $float_value;
?>
Upvotes: 0
Reputation: 26755
list($hours, $minutes) = explode(':', $input);
echo $hours . '.' . $minutes / 60 * 100;
Upvotes: 1