Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Time String to Decimal Hours PHP [closed]

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.

like image 404
JoshMWilliams Avatar asked Nov 28 '12 00:11

JoshMWilliams


People also ask

How do I convert time to a decimal 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.

How to convert strings to numbers in PHP?

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:

How to convert hours and minutes into a decimal number?

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

How do you convert time to seconds in math?

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


1 Answers

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;

?>
like image 67
Fábio Duque Silva Avatar answered Sep 24 '22 04:09

Fábio Duque Silva