Convert seconds to Hour:Minute:Second

2018-12-31 10:00发布

I need to convert seconds to "Hour:Minute:Second".

For example: "685" converted to "00:11:25"

How can I achieve this?

标签: php time
23条回答
步步皆殇っ
2楼-- · 2018-12-31 10:23

Other solutions use gmdate, but fail in edge cases where you have more than 86400 seconds. To get around this, we can simply compute the number of hours ourselves, then let gmdate compute the remaining seconds into minutes/seconds.

echo floor($seconds / 3600) . gmdate(":i:s", $seconds % 3600);

Input: 6030 Output: 1:40:30

Input: 2000006030 Output: 555557:13:50

查看更多
妖精总统
3楼-- · 2018-12-31 10:23

See:

    /** 
     * Convert number of seconds into hours, minutes and seconds 
     * and return an array containing those values 
     * 
     * @param integer $inputSeconds Number of seconds to parse 
     * @return array 
     */ 

    function secondsToTime($inputSeconds) {

        $secondsInAMinute = 60;
        $secondsInAnHour  = 60 * $secondsInAMinute;
        $secondsInADay    = 24 * $secondsInAnHour;

        // extract days
        $days = floor($inputSeconds / $secondsInADay);

        // extract hours
        $hourSeconds = $inputSeconds % $secondsInADay;
        $hours = floor($hourSeconds / $secondsInAnHour);

        // extract minutes
        $minuteSeconds = $hourSeconds % $secondsInAnHour;
        $minutes = floor($minuteSeconds / $secondsInAMinute);

        // extract the remaining seconds
        $remainingSeconds = $minuteSeconds % $secondsInAMinute;
        $seconds = ceil($remainingSeconds);

        // return the final array
        $obj = array(
            'd' => (int) $days,
            'h' => (int) $hours,
            'm' => (int) $minutes,
            's' => (int) $seconds,
        );
        return $obj;
    }

From: Convert seconds into days, hours, minutes and seconds

查看更多
何处买醉
4楼-- · 2018-12-31 10:26

You can use the gmdate() function:

echo gmdate("H:i:s", 685);
查看更多
其实,你不懂
5楼-- · 2018-12-31 10:26

Use function gmdate() only if seconds are less than 86400 (1 day) :

$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05

See: gmdate()

Run the Demo


Convert seconds to format by 'foot' no limit* :

$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05

See: floor(), sprintf(), arithmetic operators

Run the Demo


Example use of DateTime extension:

$seconds = 8525;
$zero    = new DateTime("@0");
$offset  = new DateTime("@$seconds");
$diff    = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05

See: DateTime::__construct(), DateTime::modify(), clone, sprintf()

Run the Demo


MySQL example range of the result is constrained to that of the TIME data type, which is from -838:59:59 to 838:59:59 :

SELECT SEC_TO_TIME(8525);
# 02:22:05

See: SEC_TO_TIME

Run the Demo


PostgreSQL example:

SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05

Run the Demo

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 10:26
<?php
$time=3*3600 + 30*60;


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

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

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

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

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

$second=floor($time);
$time-=$second;
if($year>0){
    echo $year." year, ";
}
if($month>0){
    echo $month." month, ";
}
if($day>0){
    echo $day." day, ";
}
if($hour>0){
    echo $hour." hour, ";
}
if($minute>0){
    echo $minute." minute, ";
}
if($second>0){
    echo $second." second, ";
}
查看更多
妖精总统
7楼-- · 2018-12-31 10:28

Solution from: https://gist.github.com/SteveJobzniak/c91a8e2426bac5cb9b0cbc1bdbc45e4b

Here is a very clean and short method!

This code avoids as much as possible of the tedious function calls and piece-by-piece string-building, and the big and bulky functions people are making for this.

It produces "1h05m00s" format and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.

And it skips all empty leading components to avoid giving you useless info like "0h00m01s" (instead that will show up as "1s").

Example results: "1s", "1m00s", "19m08s", "1h00m00s", "4h08m39s".

$duration = 1; // values 0 and higher are supported!
$converted = [
    'hours' => floor( $duration / 3600 ),
    'minutes' => floor( ( $duration / 60 ) % 60 ),
    'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }

If you want to make the code even shorter (but less readable), you can avoid the $converted array and instead put the values directly in the sprintf() call, as follows:

$duration = 1; // values 0 and higher are supported!
$result = ltrim( sprintf( '%02dh%02dm%02ds', floor( $duration / 3600 ), floor( ( $duration / 60 ) % 60 ), ( $duration % 60 ) ), '0hm' );
if( $result == 's' ) { $result = '0s'; }

Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead:

$duration = -493; // negative values are supported!
$wasNegative = FALSE;
if( $duration < 0 ) { $wasNegative = TRUE; $duration = abs( $duration ); }
$converted = [
    'hours' => floor( $duration / 3600 ),
    'minutes' => floor( ( $duration / 60 ) % 60 ),
    'seconds' => ( $duration % 60 )
];
$result = ltrim( sprintf( '%02dh%02dm%02ds', $converted['hours'], $converted['minutes'], $converted['seconds'] ), '0hm' );
if( $result == 's' ) { $result = '0s'; }
if( $wasNegative ) { $result = "-{$result}"; }
// $result is now "-8m13s"
查看更多
登录 后发表回答