-1

Is there a built-in php function that converts number of seconds to military time?

So it will take 3600 and output 01:00:00.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
John
  • 32,403
  • 80
  • 251
  • 422

4 Answers4

2

Try this:

<?php
$seconds = 3600;
echo sprintf("%02d:%02d:%02d",$seconds/3600,($seconds/60)%60,$seconds%60);
?>
bozdoz
  • 12,550
  • 7
  • 67
  • 96
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` every time. – mickmackusa Apr 08 '22 at 09:52
1
$seconds = 3600;
echo date('H:i:s', $seconds);
  • how come that gives me 20:00:00? Will `echo date('H:i:s', 3600-19*3600);` work on EVERY server? – John Mar 07 '12 at 16:44
  • 1
    `date` actually depends on the current timezone. I didn't think of that. You can use `date_default_timezone_set('UTC');` but that is kinda ugly. –  Mar 07 '12 at 16:46
1

There you go. I might have a use for such a function myself sometime, so I wrote that for you.

function time_format($time)  {
    if($time > 86400) {
        return "more than 1 day";
    }

    $display = '';
    if ($time >= 3600) {
        $hours = floor($time/3600);
        $time = $time%3600;
        if($hours <= 9) { $display .= "0"; }
        $display .= $hours;
    } else {
        $display .= "00";
    } 
    $display .= ":";
    if($time >= 60) {
        $minutes = floor($time/60);
        $time = $time%60;
        if($minutes <= 9) { $display .= "0"; }
        $display .= $minutes;
    } else {
        $display .= "00";
    }
    $display .= ":";
    if($time > 0) {
        $seconds = $time;
        if($seconds <= 9) { $display .= "0"; }
        $display .= $seconds;
    } else {
        $display .= "00";
    }
    return $display;
}

EDIT: seeing bozdoz's answer makes me feel deeply ashamed :(

DerShodan
  • 463
  • 7
  • 16
1
$seconds = 3600;
echo gmdate('H:i:s', $seconds);

xato was nearly there.

With this approach it's a little bit of a cheat but I believe it will behave in exactly the way that you want it to with hours, minutes and seconds.

edit: and the behaviour will be consistent across all servers regardless of their TZ settings

James C
  • 14,047
  • 1
  • 34
  • 43