将负秒转换为hh:mm:ss格式

时间:2017-06-23 08:27:13

标签: php

wanne有一个在Timeformat h:i:s

中转换正负秒的函数

所以我有价值

$seconds= -41880;

尝试第一个功能

 function secToHR($seconds) 
        {


        $hours = floor($seconds / 3600);
        $mins = floor($seconds / 60 % 60);
        $secs = floor($seconds % 60);
        $time = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);

        return $time;

        }

结果是

$time = -12:-38:00 

当我使用$ seconds的正值时

$seconds = 100380

然后结果就像

$time =     27:53:00

什么是正确的

然后是第二个功能

function secToHR2($seconds)
    {
    $time    = gmdate("h:i:s", abs($seconds));
    if ($seconds < 0) {
    $time = '-' . $time;
    }
    return $time;
    }

有      $ seconds = -41880

结果

 $time =    -11:38:00

这是正确的

但是

$seconds = 100380

结果现在是

$time : 03:53:00

现在错了

是否有人知道我需要和修改哪些功能以便正确处理正负值

2 个答案:

答案 0 :(得分:1)

最简单的方法是

  1. 提取任何负号
  2. 调用您的函数,该函数仅定义为正值(secToHR
  3. 如果适当,重新插入负号

答案 1 :(得分:1)

gmdate()(以及其他date-time functions)表示作为参数作为日期传递的秒数,而不是小时数,分钟数和秒数。它永远不会为h返回大于23的值,依此类推。

结合两个函数的逻辑:使用secToHR()的代码格式化其参数的绝对值和secToHR2()的逻辑来处理符号。

function secToHR($seconds) 
{
    // Separate the sign and the absolute value of $seconds
    $sign = '';
    if ($seconds < 0) {
        $sign    = '-';
        $seconds = -$seconds;
    }

    // Compute the components
    $secs = $seconds % 60;
    $minutes = ($seconds - $secs) / 60;
    $mins = $minutes % 60;
    $hours = ($minutes - $mins) / 60;

    // P
    return sprintf('%s%02d:%02d:%02d', $sign, $hours, $mins, $secs);
}