61
  1. My output is in the format of 290.52262423327 seconds. How can i change this to 00:04:51?

  2. The same output i want to show in seconds and in HH:MM:SS format, so if it is seconds, i want to show only 290.52 seconds.(only two integers after decimal point)? how can i do this?

I am working in php and the output is present in $time variable. want to change this $time into $newtime with HH:MM:SS and $newsec as 290.52.

Thanks :)

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
Scorpion King
  • 1,878
  • 8
  • 38
  • 45
  • Are you looking for a duration or a time stamp? – Rob K Aug 20 '10 at 20:22
  • duplicate of **[Convert seconds into days, hours, minutes and seconds](http://stackoverflow.com/a/19680778/67332)** or **[Convert seconds to Hour:Minute:Second](http://stackoverflow.com/a/20870843/67332)** – Glavić Jan 01 '14 at 16:59
  • possible duplicate of [Convert seconds to Hour:Minute:Second](http://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond) – PeerBr Oct 08 '14 at 00:03
  • What have you tried so far? Where are you stuck? If you could show the code that is used, it could help to spot the problem – Nico Haase Jan 22 '22 at 14:30

16 Answers16

131

1)

function foo($seconds) {
  $t = round($seconds);
  return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}

echo foo('290.52262423327'), "\n";
echo foo('9290.52262423327'), "\n";
echo foo(86400+120+6), "\n";

prints

00:04:51
02:34:51
24:02:06

2)

echo round($time, 2);
Nick F
  • 9,781
  • 7
  • 75
  • 90
VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • I ran into some extreme unsuccessful divisions and subtracting functions trying to achieve what you did in that one line :) `sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60)` – adrianTNT Dec 19 '13 at 15:10
24

Try this one

echo gmdate("H:i:s", 90);
Azam Alvi
  • 6,918
  • 8
  • 62
  • 89
  • This solution will work for any values less than the number of seconds in a day, but will reset to 00:00:00 for values ≥ 86400. – dctucker Nov 23 '16 at 23:35
  • 2
    any idea on how to make it work for values >86400 ?? – Vinod Kumar Jun 28 '17 at 04:26
  • This is misleading: `gmdate()` accepts a Unix timestamp as the second argument, so effectively you are getting the "H:i:s" portion 90 seconds after January 1 1970 00:00:00 GMT, of course if you go over the number of seconds in a day (86400), you will be getting the "H:i:s" portion of the next day. Only use this if you are guaranteed to always have less than a day's worth of seconds. – Duncanmoo Jan 11 '22 at 11:33
4

Edit: A comment pointed out that the previous answer fails if the number of seconds exceeds a day (86400 seconds). Here's an updated version. The OP did not specify this requirement so this may be implemented differently than the OP might expect, and there may be much better answers here already. I just couldn't stand having provided an answer with this bug.

$iSecondsIn = 290.52262423327;

// Account for days.
$iDaysOut = 0;
while ($iSecondsIn >= 86400) {
    $iDaysOut += 1;
    $iSecondsIn -= 86400;
}

// Display number of days if appropriate.
if ($iDaysOut > 0) {
    print $iDaysOut.' days and ';
}

// Print the final product.
print date('H:i:s', mktime(0, 0, $iSecondsIn));

The old version, with the bug:

$iSeconds = 290.52262423327;
print date('H:i:s', mktime(0, 0, $iSeconds));
Teekin
  • 12,581
  • 15
  • 55
  • 67
  • This answer is also going to be problematic if your `$iSeconds` goes over 86399 (the number of seconds in a day). 86401 will give you 00:00:01. – Duncanmoo Jan 12 '22 at 12:00
  • Thank you for pointing that out. I've updated the answer accordingly. – Teekin Mar 20 '22 at 13:18
4

For till 23:59:59 hours you can use PHP default function

echo gmdate("H:i:s", 86399);

Which will only return the result till 23:59:59

If your seconds is more then 86399 than with the help of @VolkerK answer

$time = round($seconds);
echo sprintf('%02d:%02d:%02d', ($time/3600),($time/60%60), $time%60);

will be the best options to use ...

Mannu saraswat
  • 1,061
  • 8
  • 15
2

Try this:

$time = 290.52262423327;
echo date("h:i:s", mktime(0,0, round($time) % (24*3600)));
MartyIX
  • 27,828
  • 29
  • 136
  • 207
2

Based on https://stackoverflow.com/a/3534705/4342230, but adding days:

function durationToString($seconds) {
  $time = round($seconds);

  return sprintf(
    '%02dD:%02dH:%02dM:%02dS',
    $time / 86400,
    ($time / 3600) % 24,
    ($time / 60) % 60,
    $time % 60
  );
}
GuyPaddock
  • 2,233
  • 2
  • 23
  • 27
1

I dont know if this is the most efficient way, but if you also need to display days, this works:

function foo($seconds) { 
$t = round($seconds); 
return sprintf('%02d  %02d:%02d:%02d', ($t/86400%24), ($t/3600) -(($t/86400%24)*24),($t/60%60), $t%60);
}
Serge
  • 312
  • 5
  • 20
1

Try this :)

private function conversionTempsEnHms($tempsEnSecondes)
    {
        $h = floor($tempsEnSecondes / 3600);
        $reste_secondes = $tempsEnSecondes - $h * 3600;

        $m = floor($reste_secondes / 60);
        $reste_secondes = $reste_secondes - $m * 60;

        $s = round($reste_secondes, 3); 
        $s = number_format($s, 3, '.', '');

        $h = str_pad($h, 2, '0', STR_PAD_LEFT);
        $m = str_pad($m, 2, '0', STR_PAD_LEFT);
        $s = str_pad($s, 6, '0', STR_PAD_LEFT);

        $temps = $h . ":" . $m . ":" . $s;

        return $temps;
    }
Zagloo
  • 1,297
  • 4
  • 17
  • 34
1

Personally, going off other peoples answers I made my own parser. Works with days, hours, minutes and seconds. And should be easy to expand to weeks/months etc. It works with deserialisation to c# as well

function secondsToTimeInterval($seconds) {
    $t = round($seconds);
    $days = floor($t/86400);
    $day_sec = $days*86400;
    $hours = floor( ($t-$day_sec) / (60 * 60) );
    $hour_sec = $hours*3600;
    $minutes = floor((($t-$day_sec)-$hour_sec)/60);
    $min_sec = $minutes*60;
    $sec = (($t-$day_sec)-$hour_sec)-$min_sec;
    return sprintf('%02d:%02d:%02d:%02d', $days, $hours, $minutes, $sec);
}
0

1)

$newtime = sprintf( "%02d:%02d:%02d", $time / 3600, $time / 60 % 60, $time % 60 );

2)

$newsec = sprintf( "%.2f", $time );
Rob K
  • 8,757
  • 2
  • 32
  • 36
0

If you're using Carbon (such as in Laravel), you can do this:

$timeFormatted = \Carbon\Carbon::now()->startOfDay()->addSeconds($seconds)->toTimeString();

But $timeFormatted = date("H:i:s", $seconds); is probably good enough.

Just see caveats.

Ryan
  • 22,332
  • 31
  • 176
  • 357
0

Here was my implementation with microseconds

    /**
     * @example 00 d 00 h 00 min 00 sec 005098 ms (0.005098 sec.ms)
     */
    public function __toString()
    {
        // Add your code to get $seconds and $microseconds
        $time = round(($seconds + $microseconds), 6, PHP_ROUND_HALF_UP);

        return sprintf(
            '%02d d %02d h %02d min %02d sec %06d ms (%s sec.ms)',
            $time / 86400,
            ($time / 3600) % 24,
            ($time / 60) % 60,
            $time % 60,
            $time * 1000000 % 1000000,
            $time
        );
    }
William Desportes
  • 1,412
  • 1
  • 22
  • 31
0
echo date('H:i:s', round($time)%86400);
0

Simple formatter with progressively added parts - sample:

  • formatTime(123) => 2m 3s
  • formatTime(7400) => 2h 3m 20s
  • formatTime(999999) => 11d 13h 46m 39s

function formatTime($secs)
{
    $secs = max(0, intval($secs));
    if($secs > 0){
        $out = [];
        $yrs = floor($secs / 31536e3);
        if($yrs){
            $out[] = $yrs."y";
        }
        $rem = $secs - $yrs * 31536e3;
        $days = floor($rem / 86400);
        if($days || $out){
            $out[] = $days."d";
        }
        $rem -= $days * 86400;
        $hrs = floor($rem / 3600);
        if($hrs || $out){
            $out[] = $hrs."h";
        }
        $rem -= $hrs * 3600;
        $min = floor($rem / 60);
        if($min || $out){
            $out[] = $min."m";
        }
        $rem -= $min * 60;
        $out[] = $rem."s";
        return implode(" ", $out);
    }
    return 0;
}
lubosdz
  • 4,210
  • 2
  • 29
  • 43
-1
echo date('H:i:s',$time);

echo number_format($time,2);
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
-1

Numero uno... http://www.ckorp.net/sec2time.php (use this function)

Numero duo... echo round(290.52262423327,2);

Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66