【问题标题】:PHP round the time to the nearest 15 secondsPHP 将时间四舍五入到最接近的 15 秒
【发布时间】:2014-12-12 10:21:54
【问题描述】:

这不是一个重复的问题,而是涉及到对时间的一点理解。

我需要解决以下问题 我有一些特别制作的时间(基于日期),需要四舍五入到最接近的 15 秒:

60 秒是 1 分钟 意思是常规的圆形,地板,天花板是最接近的小数(10/5) 这对我没有时间帮助。 也因为我正在处理秒,可能是 59:59 将四舍五入到最接近的小时:例如17:59:59 应该是 18:00。

示例:

6:17:29 舍入为 6:17:30 6:29:55 四舍五入为 6:30:00 20:45:34 舍入为 20:45:30

下面的代码做了一些工作:

$hr = date('H',($resultStr));
$mn = date('i',($resultStr));
$sc = date('s',($resultStr));

$tot = ($hr * 60 * 60) + ($mn * 60) + $sc;
$totd = $tot / (60);
$totc = ceil($totd);
$totc = $totc / 60;
$hr = floor($totc);
$mn = ($totc - $hr)*60;
$mnflr = floor($mn);
$mn2 = $mn - $mnflr;
echo "$hr:$mnflr";

这会导致: 18:35:17 四舍五入为:18:36(这是错误的) 18:31:49 四舍五入为:18:32(这是错误的)

顺便说一句:

$secs = date('U',($resultStr));
$round = ceil ( (($secs / 60 ) * 60 ));
$newtime = date('H:i:s',($round));

产生:18:42:58 四舍五入为:18:42:58,这也是不正确的

请提前谢谢你......

【问题讨论】:

    标签: php time rounding seconds


    【解决方案1】:

    您过于复杂了,只需在 Unix 时间戳级别上进行四舍五入:

    function roundMyTime($time)
    {
      $time = strtotime($time);
      $time = 15*round($time/15);
      echo date('H:i:s', $time)."\n";
    }
    roundMyTime('18:35:17');
    roundMyTime('18:35:27');
    roundMyTime('18:35:37');
    roundMyTime('18:35:47');
    roundMyTime('18:35:57');
    roundMyTime('18:36:07');
    roundMyTime('18:36:17');
    

    输出:

    18:35:15
    18:35:30
    18:35:30
    18:35:45
    18:36:00
    18:36:00
    18:36:15
    

    Demo here.

    【讨论】:

      【解决方案2】:

      使用strtotime 将日期转换为秒,然后只需几秒即可工作。

      $seconds = strtotime($date);
      $seconds /= 15;
      $seconds = round($seconds);
      $seconds *= 15;
      $date = date("Y-m-d H:i:s", $seconds);
      

      【讨论】:

        【解决方案3】:
        $seconds = ($hr * 60 + $mn) * 60 + $sc; // convert to seconds
        $rounded = round($seconds/15)*15;       // round
        $sc = $rounded % 60;                    // get seconds
        $mn = ($rounded - $sc) / 60 % 60;       // get minutes
        $hr = ($rounded - $sc - $mn * 60) / 60; // get hours
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-11
          • 2018-05-27
          • 1970-01-01
          • 1970-01-01
          • 2018-06-03
          • 1970-01-01
          • 1970-01-01
          • 2011-01-22
          相关资源
          最近更新 更多