我需要将秒转换为“小时:分钟:秒”。

例如:“685”转换为“00:11:25”

我怎样才能做到这一点呢?


当前回答

我已经在这里解释过了 把答案也粘贴到这里

在23:59:59小时之前,您可以使用PHP默认函数

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

只会返回结果直到23:59:59

如果你的秒数大于86399 在@VolkerK的帮助下回答

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

将是使用…的最佳选择。

其他回答

// TEST
// 1 Day 6 Hours 50 Minutes 31 Seconds ~ 111031 seconds

$time = 111031; // time duration in seconds

$days = floor($time / (60 * 60 * 24));
$time -= $days * (60 * 60 * 24);

$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);

$minutes = floor($time / 60);
$time -= $minutes * 60;

$seconds = floor($time);
$time -= $seconds;

echo "{$days}d {$hours}h {$minutes}m {$seconds}s"; // 1d 6h 50m 31s
gmdate("H:i:s", no_of_seconds);

如果no_of_seconds大于1天(一天中的秒数),将不会以H:i:s格式给出时间。 它将忽略日值,只给出小时:分钟:秒

例如:

gmdate("H:i:s", 89922); // returns 0:58:42 not (1 Day 0:58:42) or 24:58:42

任何人在未来寻找这个,这给了最初的海报要求的格式。

$init = 685;
$hours = floor($init / 3600);
$hrlength=strlen($hours);
if ($hrlength==1) {$hrs="0".$hours;}
else {$hrs=$hours;} 

$minutes = floor(($init / 60) % 60);
$minlength=strlen($minutes);
if ($minlength==1) {$mins="0".$minutes;}
else {$mins=$minutes;} 

$seconds = $init % 60;
$seclength=strlen($seconds);
if ($seclength==1) {$secs="0".$seconds;}
else {$secs=$seconds;} 

echo "$hrs:$mins:$secs";

这是一种很好的方法:

function time_converter($sec_time, $format='h:m:s'){
      $hour = intval($sec_time / 3600) >= 10 ? intval($sec_time / 3600) : '0'.intval($sec_time / 3600);
      $minute = intval(($sec_time % 3600) / 60) >= 10 ? intval(($sec_time % 3600) / 60) : '0'.intval(($sec_time % 3600) / 60);
      $sec = intval(($sec_time % 3600) % 60)  >= 10 ? intval(($sec_time % 3600) % 60) : '0'.intval(($sec_time % 3600) % 60);

      $format = str_replace('h', $hour, $format);
      $format = str_replace('m', $minute, $format);
      $format = str_replace('s', $sec, $format);

      return $format;
    }

不知道为什么还没有提出这个建议,但是这里有一个使用DateInterval的变体,它的优点是秒> 86400不是问题(只是不要期望小时< 24)

noteable:该函数返回DateInterval对象,因此输出格式由调用者决定

function seconds2interval($seconds) {
    $s = intval($seconds);
    $hrs = floor($s / 3600);
    $min = floor(($s - ($hrs * 3600)) / 60);
    $sec = $s % 60;
    
    $duration = sprintf('PT%dH%dM%dS', $hrs, $min, $sec);
    $d = new DateInterval($duration);
    
    return $d;
}

$d = seconds2interval(93837.3113);  
echo $d->format('%H:%I:%s'); // 26:03:57