Convert Time String to Decimal Hours PHP

14,262

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;

?>
Share:
14,262
JoshMWilliams
Author by

JoshMWilliams

Computer and Aviation Geek

Updated on June 08, 2022

Comments

  • JoshMWilliams
    JoshMWilliams almost 2 years

    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.

  • Fábio Duque Silva
    Fábio Duque Silva over 11 years
    Had an error in the return line (in the seconds part). It's $hms[2]/3600 and not $hms[1]/3600. Sorry.