【问题标题】:How to convert decimal seconds to time with fractional seconds in PHP如何在 PHP 中将小数秒转换为带小数秒的时间
【发布时间】:2018-05-03 09:42:00
【问题描述】:

我正在尝试解决一个问题,我需要能够以秒为单位将时间转换为带小数位的时间,例如 375.844 我需要将其转换为以下格式: HH:MM:SS.0 而不是四舍五入到最接近的整秒 我相信上面的数字应该显示为00:06:15.8

这是一个更广泛的程序的一部分,用户可以在其中输入小时、分钟和秒,允许十分之一秒。

我使用以下函数将这一切转换为秒:

public function timetosecs() {
    return $this->hours * (60 * 60) + $this->mins * 60 + $this->secs * 1;
}

然后它对秒执行一些计算以调整它们,乘以因子0.866,然后这是将它们转换回时间格式的函数,但它似乎不显示十分位。

  public function secstotime($totalSeconds) {
    $hours = floor($totalSeconds / 3600);
    $totalSeconds %= 3600;
    $minutes = floor($totalSeconds / 60);
    $seconds = floor(($totalSeconds % 60) * 10) / 10;
    return $hours . ":" . $minutes . ":" . $seconds;
}

【问题讨论】:

    标签: php time


    【解决方案1】:

    使用sprintf()函数设置前导数字:

    function secstotime($totalSeconds) {
        $startTotalSeconds = $totalSeconds;
        $hours = floor($totalSeconds / 3600);
        $totalSeconds %= 3600;
        $minutes = floor($totalSeconds / 60);
        $seconds = $startTotalSeconds - ($minutes * 60);
        return sprintf("%02d",$hours) . ":" . sprintf("%02d",$minutes) . ":" .sprintf("%.1f", $seconds);
    }
    
    
    //...
    echo secstotime(375.844); // prints 00:06:15.8
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-29
      • 2023-02-23
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 2020-11-13
      • 2021-10-29
      相关资源
      最近更新 更多