【问题标题】:Round Datetime to the next 15 minutes将日期时间舍入到接下来的 15 分钟
【发布时间】:2019-06-17 22:34:41
【问题描述】:

在我的项目中,我需要将日期时间四舍五入,例如“08:10”到“08:00”。

更多示例

"8:20 到 8:15" "8:31 到 8:30"

在下一步中,我需要一个额外的方法来四舍五入。

示例 “8:20 到 8:30” "8:31 到 8:45"

$shiftInPre = new \DateTime($row["time_start"] /* <-e.g. 8:02*/);
echo roundtoLastQuarterHour($shiftInPre);

【问题讨论】:

标签: php html time


【解决方案1】:

如果您只有 H:i 而不是完整的日期时间,请使用基本的字符串操作

$shiftInPre = '8:07';
list($hours, $mins) = explode(':', $shiftInPre);
$mins = $hours * 60 + $mins;

$rounded = round($mins / 15) * 15;
echo floor($rounded / 60) . ':' . str_pad($rounded % 60, 2, 0); 
// 8:07 >> 8:00
// 8:08 >> 8:15
// 8:18 >> 8:15

【讨论】:

    【解决方案2】:

    如果您真的需要/想要使用DateTime-Objects,您可以使用基于分钟的modify-方法操作DateTime-Object,然后使用setTime 将秒和微秒归零-方法。

    // round (floor)
    $date = new DateTime('2019-01-01T15:03:01.012345Z');
    $i = $date->format('i') % 15;
    $date->modify("-{$i} minute");
    $date->setTime($date->format('H'), $date->format('i'), 0, 0);
    var_dump($date);
    
    // round (ceil)
    $date = new DateTime('2019-01-01T15:03:01.012345Z');
    $i = 15 - ($date->format('i') % 15);
    $date->modify("+{$i} minute");
    $date->setTime($date->format('H'), $date->format('i'), 0, 0);
    var_dump($date);
    

    演示:https://3v4l.org/MIGiG

    这种方法有利于正确处理四舍五入到第二天的时间。

    但如果您只需要“舍入”一个包含小时和分钟的简单字符串,那么涉及爆炸和简单数学的解决方案就足够了(请参阅:Answer posted panther)。

    【讨论】:

      猜你喜欢
      • 2013-10-17
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2011-01-12
      相关资源
      最近更新 更多