-1

I am currently converting minutes to hours & minutes by using this function:

function minToHourMin($time) {
    $minutes = $time%60;
    $hours = floor($time/60);
    return $hours . ':' . $minutes;
}

However, it doesn't work as expected when displaying the minutes that are < 10.

For example running the function with 61 minutes would return:

1:1 instead of the intended 1:01

Thanks

Priscilla Jobin
  • 609
  • 7
  • 19
Dan P.
  • 1,707
  • 4
  • 29
  • 57
  • 2
    This has nothing to do with converting, but everything to do with converting the number to the appropriate string. Use `sprintf` with the `%02d` format specifier. Make sure to focus on the real problem and remove unnecessary context. – user2246674 Jun 17 '13 at 05:15
  • or `str_pad($minutes, 2, '0', STR_PAD_LEFT);` – Sam Jun 17 '13 at 05:16
  • Thanks! The return line is now: return sprintf('%2d:%02d', $hours, $minutes); – Dan P. Jun 17 '13 at 05:21
  • possible duplicate of [Zero-pad digits in string](http://stackoverflow.com/questions/324358/zero-pad-digits-in-string) – webbiedave Jun 17 '13 at 05:21

2 Answers2

0

You need

sprintf('%08d', $minutes);

So the function would be

function minToHourMin($time) {
    $minutes = $time%60;
    $minutes = sprintf('%08d', $minutes);
    $hours = floor($time/60);
    return $hours . ':' . $minutes;
}
Ali
  • 3,479
  • 4
  • 16
  • 31
0

Do it all at once:

return sprintf('%02d:%02d', floor($time/60), $time%60);