把秒数转成“时:分:秒”的格式

<?php
/**
 * 把秒数转成“时:分:秒”的格式
 *
 * @param int $seconds 秒数
 * @return string 时:分:秒
 */
function seconds_format($seconds)
{
    if ($seconds > 3600) {
        $hours = (int)($seconds / 3600);
        $hours = $hours > 9 ? $hours : "0{$hours}"; // 不足两位数左侧补零
        $format = "{$hours}:" . gmstrftime('%M:%S', $seconds);
    } else {
        $format = gmstrftime('%H:%M:%S', $seconds);
    }

    return $format;
}

echo seconds_format(0) . PHP_EOL;     // 00:00:00
echo seconds_format(8) . PHP_EOL;     // 00:00:08
echo seconds_format(59) . PHP_EOL;    // 00:00:59
echo seconds_format(60) . PHP_EOL;    // 00:01:00
echo seconds_format(61) . PHP_EOL;    // 00:01:01
echo seconds_format(365) . PHP_EOL;   // 00:06:05
echo seconds_format(3599) . PHP_EOL;  // 00:59:59
echo seconds_format(3600) . PHP_EOL;  // 01:00:00
echo seconds_format(3601) . PHP_EOL;  // 01:00:01
echo seconds_format(86399) . PHP_EOL; // 23:59:59
echo seconds_format(86400) . PHP_EOL; // 24:00:00
echo seconds_format(86401) . PHP_EOL; // 24:00:01

Copyright © 2024 码农人生. All Rights Reserved