PHP 将秒转换为hh:mm:ss

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 将秒转换为hh:mm:ss相关的知识,希望对你有一定的参考价值。

function sec2hms ($sec, $padHours = false) {

    $hms = "";
    
    // there are 3600 seconds in an hour, so if we
    // divide total seconds by 3600 and throw away
    // the remainder, we've got the number of hours
    $hours = intval(intval($sec) / 3600); 

    // add to $hms, with a leading 0 if asked for
    $hms .= ($padHours) 
          ? str_pad($hours, 2, "0", STR_PAD_LEFT). ':'
          : $hours. ':';
     
    // dividing the total seconds by 60 will give us
    // the number of minutes, but we're interested in 
    // minutes past the hour: to get that, we need to 
    // divide by 60 again and keep the remainder
    $minutes = intval(($sec / 60) % 60); 

    // then add to $hms (with a leading 0 if needed)
    $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ':';

    // seconds are simple - just divide the total
    // seconds by 60 and keep the remainder
    $seconds = intval($sec % 60); 

    // add to $hms, again with a leading 0 if needed
    $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);

    return $hms;
}

以上是关于PHP 将秒转换为hh:mm:ss的主要内容,如果未能解决你的问题,请参考以下文章

使用 JavaScript 将秒转换为 HH-MM-SS?

使用 Prometheus 和 Grafana 将秒转换为 HH:MM:SS

s-s-rS2016 将秒转换为 hh:mm:ss 格式

使用 JavaScript 将秒转换为 HH-MM?

仅在 javascript 中将 HH:MM:SS 字符串转换为秒

将秒转换为一天中的时间