PHP如何将时间向下取整至整点?
时间向下取整到整点的实现方案
一、针对DateTime/DateTimeImmutable类型
你完全可以直接通过getHour()方法获取当前时间的小时数,再调用setTime()把分、秒设为0,代码示例如下:
DateTimeImmutable示例:
$dt = new DateTimeImmutable('14:50:35'); $roundedDt = $dt->setTime($dt->getHour(), 0, 0); echo $roundedDt->format('H:i:s'); // 输出14:00:00
DateTime示例(可变对象):
$dt = new DateTime('14:50:35'); $dt->setTime($dt->getHour(), 0, 0); echo $dt->format('H:i:s'); // 输出14:00:00
另外用modify()方法可以一步到位,写法更简洁:
$dt = new DateTimeImmutable('14:50:35'); $roundedDt = $dt->modify('floor hour'); echo $roundedDt->format('H:i:s'); // 输出14:00:00
二、针对Unix时间戳类型
你的猜测是对的,利用小时对应的秒数(3600秒)做除法取整即可:
$timestamp = strtotime('14:50:35'); // 示例时间戳 $roundedTimestamp = floor($timestamp / 3600) * 3600; // 转成可读时间验证 echo date('H:i:s', $roundedTimestamp); // 输出14:00:00
如果要把处理后的时间戳转回DateTimeImmutable对象:
$roundedDt = DateTimeImmutable::createFromFormat('U', $roundedTimestamp); echo $roundedDt->format('H:i:s'); // 输出14:00:00
三、兼容多种输入类型的通用函数
如果需要同时支持多种输入类型,可以写一个简单的封装函数:
function roundDownToHour(mixed $time): DateTimeImmutable { if ($time instanceof DateTimeInterface) { return $time instanceof DateTimeImmutable ? $time->setTime($time->getHour(), 0, 0) : DateTimeImmutable::createFromInterface($time)->setTime($time->getHour(), 0, 0); } elseif (is_numeric($time)) { $roundedTimestamp = floor((int)$time / 3600) * 3600; return DateTimeImmutable::createFromFormat('U', $roundedTimestamp); } else { throw new InvalidArgumentException('Unsupported time type'); } } // 测试示例 echo roundDownToHour('14:50:35')->format('H:i:s'); // 输出14:00:00 echo roundDownToHour(strtotime('14:50:35'))->format('H:i:s'); // 输出14:00:00 echo roundDownToHour(new DateTime('14:50:35'))->format('H:i:s'); // 输出14:00:00
内容的提问来源于stack exchange,提问作者user32457645
相关产品推荐
相关产品推荐

