Formatting Duration (time) in PHP

Viewed 21596

Outputting from a directions api I have a duration it will take the user to get from a to b. At the moment it is minutes but if the users journey will take 3 hours and 20 minutes it will output 200 minutes.

I would like it to work out that that is greater than 60 minutes. then divide by 60 and add the remainder to give

3 hours 20 minutes.

How do we do this.

Marvellous

9 Answers

For those who need it... Minutes to Period of Time - PT:

<?php
function pttime($time, $format)
{
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);

    //is PT
    if ($format == 'PT') {

        //full hour
        if (($hours > 0) && ($minutes == 0)) {
            $time_result = 'PT' . $hours . 'H';
        }

        //hour and minutes
        if (($hours > 0) && ($minutes <> 0)) {
            $time_result = 'PT' . $hours . 'H' . $minutes . 'M';
        }

        //just minutes
        if ($hours == 0) {
            $time_result = 'PT' . $minutes . 'M';
        }
    }

    //it's not PT
    else {
        $time_result = sprintf("%02s", $hours) . ':' . sprintf("%02s", $minutes);

    }
    return $time_result;
}

//input in minutes and its outputs
echo pttime(155,'PT'); //output -> PT2H35M
echo pttime(52,'PT');  //output -> PT52M
echo pttime(60,'PT');  //output -> PT1H
echo pttime(60,'');    //output -> 01:00
Related