将秒转换为天、小时、分钟和秒

2022-08-30 07:21:36

我想将秒的变量转换为天,小时,分钟和秒。$uptime

例:

$uptime = 1640467;

结果应该是:

18 days 23 hours 41 minutes

答案 1

这可以通过日期时间类来实现

功能:

function secondsToTime($seconds) {
    $dtF = new \DateTime('@0');
    $dtT = new \DateTime("@$seconds");
    return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}

用:

echo secondsToTime(1640467);
# 18 days, 23 hours, 41 minutes and 7 seconds

demo


答案 2

这是重写的函数,以包括天数。我还更改了变量名称,以使代码更易于理解...

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

来源: CodeAid() - http://codeaid.net/php/convert 秒到小时分秒(php)


推荐