I would like to convert time strings (Such as 2:12:0) to decimal format in hours (ex 2:12:0 would be 2.2 hours) in PHP.
Converting To And From Decimal Time In PHP. To convert a time value into a decimal value representing the number of minutes can be useful for certain calculations. The following function takes a time as a string of hh:mm:ss and returns a decimal value in minutes. * Convert time into decimal time.
It is possible to convert strings to numbers in PHP with several straightforward methods. Below, you can find the four handy methods that we recommend you to use. The first method we recommend you to use is type casting. All you need to do is casting the strings to numeric primitive data types as shown in the example below:
I am calculating hours and minutes into variables but i would like to convert this into a decimal number For example, 1 hour 30 minutes should display as 1.5 and 2 hours 15 minutes would display as 2.25 This is very simple basic Math, you should be able to do that yourself. 60 (Min in 1 hour) + 30 = 90. Then 90 / 60 = 1.5
To convert time to just seconds: 2 hours is 2 hours * (3600 seconds / 1 hour) = 2 * 3600 seconds = 7200 seconds 45 minutes is 45 minutes * (60 seconds / 1 minute) = 45 * 60 seconds = 2700 seconds 45 seconds is 45 seconds * (1 second / 1 second) = 45 * 1 seconds = 45 seconds
A fairly dumb conversion from the top of my head, using explode by colon:
<?php
$hms = "2:12:0";
$decimalHours = decimalHours($hms);
function decimalHours($time)
{
$hms = explode(":", $time);
return ($hms[0] + ($hms[1]/60) + ($hms[2]/3600));
}
echo $decimalHours;
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With