1

好的,所以我有这个功能:

function convertTime($ms){

    $sec = floor($ms/1000);
    $ms = $ms % 1000;

    $min = floor($sec/60);
    $sec = $sec % 60;
    $t = $sec;

    $hr = floor($min/60);
    $min = $min % 60;
    $t = $min;

    $day = floor($hr/60);
    $hr = $hr % 60;
    $t = $hr . " h " . $t . " m";

    return $t;
}

它将毫秒转换为 h:m,它适用于正数。例子:

echo convertTime(60000);       // outputs: 0 h 1 m
echo convertTime(60000*70);    // outputs: 1 h 10 m
echo convertTime(60000*60*48); // outputs: 48 h 0 m

(我不希望它转换为天,所以它显示实际小时数很好)不幸的是,它不能很好地处理负数......

echo convertTime(-60000);    //outputs: -1 h -1 m (should be 0 h -1 m)

关于如何弥补这一点的任何想法?

4

1 回答 1

0

这是您的原始函数,已格式化,删除了不必要的行并添加了三行:

function convertTime($ms)
{
    $sign = $ms < 0 ? "-" : "";
    $ms = abs($ms);
    $sec = floor($ms / 1000);
    $ms = $ms % 1000;
    $min = floor($sec / 60);
    $sec = $sec % 60;
    $hr = floor($min / 60);
    $min = $min % 60;
    $day = floor($hr / 60);
    $hr = $hr % 60;
    return "$sign$hr h $min m";
}
echo convertTime(+60000);      //  0 h 1 m
echo convertTime(-60000);      // -0 h 1 m
echo convertTime(-60000 * 60); // -1 h 0 m

这是我的相同功能的版本:

function convertTime($ms)
{
    $xx = $ms < 0 ? "-" : "+";
    $ms = abs($ms);
    $ss = floor($ms / 1000);
    $ms = $ms % 1000;
    $mm = floor($ss / 60);
    $ss = $ss % 60;
    $hh = floor($mm / 60);
    $mm = $mm % 60;
    $dd = floor($hh / 24);
    $hh = $hh % 24;
    return sprintf("%s%dd %02dh %02dm %02d.%04ds", $xx, $dd, $hh, $mm, $ss, $ms);
}
于 2012-12-14T12:08:17.753 回答