convert

PHP Logo

Converting To And From Decimal Time In PHP

29th November 2010 - 4 minutes read time

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.
 *
 * @param string $time The time to convert
 *
 * @return integer The time as a decimal value.
 */
function time_to_decimal($time) {
    $timeArr = explode(':', $time);
    $decTime = ($timeArr[0]*60) + ($timeArr[1]) + ($timeArr[2]/60);

    return $decTime;
}

If we take the time of 11:11:11 this gets split into 3 parts by the explode() function into hours, minutes and seconds, which then gets treated in the following way:

Minutes = (Hours x 60) + (Minutes) + (Seconds / 60)
Minutes = (11 x 60) + (11) + (11 / 60)
Minutes = (660) + (11) + (0.18333333)
Minutes = 671.18333333

The function can be used as follows:

Read the full article