将日期时间舍入到下一个15分钟

时间:2019-06-17 22:34:41

标签: php html time

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

更多示例

“ 8:20至8:15” “ 8:31到8:30”

下一步,我需要一种额外的方法来进行汇总。

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

Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.FormulaR1C1 = "PCxxx"
'this is inputting data into the last row with no data in the table in column A

Range("D" & Rows.Count).End(xlUp).Offset(0).Select
ActiveCell.FormulaR1C1 = "Userxxx"
'this is inputting data into the last row with no data in the table in column D

Range("F" & Rows.Count).End(xlUp).Offset(0).Select
ActiveCell.FormulaR1C1 = "ServiceCodexxx"
'this is inputting data into the last row with no data in the table in column F

2 个答案:

答案 0 :(得分:0)

如果您只有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

答案 1 :(得分:-1)

如果您确实需要/想使用DateTime-对象,则可以根据分钟数使用DateTime-方法操作modify-对象,然后将秒设为零, 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)。