如何将time()
的结果四舍五入(朝向未来)到下一个 5 分钟的倍数?
$now = time();
$next_five = ceil($now/300)*300;
这将给你下一轮五分钟(总是大于或等于当前时间)。
根据您的描述,我认为这就是您需要的。
尝试:
$time = round(time() / 300) * 300;
试试这个函数:
function blockMinutesRound($hour, $minutes = '5', $format = "H:i") {
$seconds = strtotime($hour);
$rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
return date($format, $rounded);
}
//call
blockMinutesRound('20:11');// return 20:10
对于使用Carbon的人(例如使用Laravel的人),这可以帮助:
/**
*
* @param CarbonCarbon $now
* @param int $nearestMin
* @param int $minimumMinutes
* @return CarbonCarbon
*/
public static function getNearestTimeRoundedUpWithMinimum($now, $nearestMin = 30, $minimumMinutes = 8) {
$nearestSec = $nearestMin * 60;
$minimumMoment = $now->addMinutes($minimumMinutes);
$futureTimestamp = ceil($minimumMoment->timestamp / $nearestSec) * $nearestSec;
$futureMoment = Carbon::createFromTimestamp($futureTimestamp);
return $futureMoment->startOfMinute();
}
这些测试断言通过:
public function testGetNearestTimeRoundedUpWithMinimum() {
$this->assertEquals('2018-07-07 14:00:00', TT::getNearestTimeRoundedUpWithMinimum(Carbon::parse('2018-07-06 14:12:59'), 60, 23 * 60 + 10)->format(TT::MYSQL_DATETIME_FORMAT));
$this->assertEquals('2018-07-06 14:15:00', TT::getNearestTimeRoundedUpWithMinimum(Carbon::parse('2018-07-06 14:12:59'), 15, 1)->format(TT::MYSQL_DATETIME_FORMAT));
$this->assertEquals('2018-07-06 14:30:00', TT::getNearestTimeRoundedUpWithMinimum(Carbon::parse('2018-07-06 14:12:59'), 30, 10)->format(TT::MYSQL_DATETIME_FORMAT));
$this->assertEquals('2018-07-06 16:00:00', TT::getNearestTimeRoundedUpWithMinimum(Carbon::parse('2018-07-06 14:52:59'), 60, 50)->format(TT::MYSQL_DATETIME_FORMAT));
$this->assertEquals(Carbon::parse('tomorrow 15:00:00'), TT::getNearestTimeRoundedUpWithMinimum(Carbon::parse('16:30'), 60, 60 * 22 + 30));
}
使用碳:
Carbon::createFromTimestamp(round(time() / 300) * 300)