Question

I would like some help converting seconds into a MM:DD:HH:MM:SS format.

I have this code here:

<?php
    // Convert seconds into months, days, hours, minutes, and seconds.
    function secondsToTime($ss) {
    $s = $ss%60;
    $m = floor(($ss%3600)/60);
    $h = floor(($ss%86400)/3600);
    $d = floor(($ss%2592000)/86400);
    $M = floor($ss/2592000);

    return "$M months, $d days, $h hours, $m minutes, $s seconds";
    }
?>

It outputs an example of

0 months, 1 days, 3 hours, 46 minutes, 39 seconds

I would just like it to be something like

00:01:03:46:39

How can I do that?

Was it helpful?

Solution

From what I gather, it looks like you're interested in returning a string with values containing two digits separaed by colons. Assuming the positioning doesn't need to change, you can do something similar to the following:

<?php
// Prefix single-digit values with a zero.
function ensure2Digit($number) {
    if($number < 10) {
        $number = '0' . $number;
    }
    return $number;
}

// Convert seconds into months, days, hours, minutes, and seconds.
function secondsToTime($ss) {
    $s = ensure2Digit($ss%60);
    $m = ensure2Digit(floor(($ss%3600)/60));
    $h = ensure2Digit(floor(($ss%86400)/3600));
    $d = ensure2Digit(floor(($ss%2592000)/86400));
    $M = ensure2Digit(floor($ss/2592000));

    return "$M:$d:$h:$m:$s";
}

Or if you don't like the thought of having one more function to manage, perhaps this may suit you better:

<?php
// Convert seconds into months, days, hours, minutes, and seconds.
function secondsToTime($ss) {
    $s = $ss%60;
    $m = floor(($ss%3600)/60);
    $h = floor(($ss%86400)/3600);
    $d = floor(($ss%2592000)/86400);
    $M = floor($ss/2592000);

    // Ensure all values are 2 digits, prepending zero if necessary.
    $s = $s < 10 ? '0' . $s : $s;
    $m = $m < 10 ? '0' . $m : $m;
    $h = $h < 10 ? '0' . $h : $h;
    $d = $d < 10 ? '0' . $d : $d;
    $M = $M < 10 ? '0' . $M : $M;

    return "$M:$d:$h:$m:$s";
}

And then to call our function (whichever method you decide to use):

<?php

$ss = 123456;
print secondsToTime($ss);

?>

OTHER TIPS

The easy way:

print date('m:d:h:i:s', $ss); // $ss = seconds

This however can't handle years the way you want it as far as I know, because it will start counting from 1970. But apparently you don't need to display years.

Alternatively, you could just format your current string with (s)printf:

printf('%02d:%02d:%02d:%02d:%02d', $M, $d, $h, $m, $s);

Given all your variables, you can simply build the string with PHP:

$str = "$M:$d:$h:$m:$s"

This code wont handle the leading zero's however.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top