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

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

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


当前回答

一小时是3600秒,一分钟是60秒,为什么不呢?

<?php

$init = 685;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;

echo "$hours:$minutes:$seconds";

?>

生产:

$ php file.php
0:11:25

(我没有测试这么多,所以地板可能会有错误)

其他回答

以防其他人正在寻找一个简单的函数来返回格式化良好的格式(我知道这不是OP要求的格式),这就是我刚刚想到的。感谢@mughal的代码,这是基于。

function format_timer_result($time_in_seconds){
    $time_in_seconds = ceil($time_in_seconds);

    // Check for 0
    if ($time_in_seconds == 0){
        return 'Less than a second';
    }

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

    // Hours
    $hours = floor($time_in_seconds / (60 * 60));
    $time_in_seconds -= $hours * (60 * 60);

    // Minutes
    $minutes = floor($time_in_seconds / 60);
    $time_in_seconds -= $minutes * 60;

    // Seconds
    $seconds = floor($time_in_seconds);

    // Format for return
    $return = '';
    if ($days > 0){
        $return .= $days . ' day' . ($days == 1 ? '' : 's'). ' ';
    }
    if ($hours > 0){
        $return .= $hours . ' hour' . ($hours == 1 ? '' : 's') . ' ';
    }
    if ($minutes > 0){
        $return .= $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ' ';
    }
    if ($seconds > 0){
        $return .= $seconds . ' second' . ($seconds == 1 ? '' : 's') . ' ';
    }
    $return = trim($return);

    return $return;
}

这是一种很好的方法:

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;
    }

下面是一个处理负秒和超过1天的秒的一行程序。

sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

例如:

$seconds= -24*60*60 - 2*60*60 - 3*60 - 4; // minus 1 day 2 hours 3 minutes 4 seconds
echo sprintf("%s:%'02s:%'02s\n", intval($seconds/60/60), abs(intval(($seconds%3600) / 60)), abs($seconds%60));

输出:26:03:04

你可以使用gmdate()函数:

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

试试这个:

date("H:i:s",-57600 + 685);

从 http://bytes.com/topic/php/answers/3917-seconds-converted-hh-mm-ss