11

如何将time()向上(朝向未来)的结果四舍五入到下一个 5 分钟的倍数?

4

5 回答 5

45
 $now = time();     
 $next_five = ceil($now/300)*300;

这将为您提供下一轮五分钟(始终大于或等于当前时间)。

根据您的描述,我认为这是您所需要的。

于 2012-04-14T00:18:03.693 回答
16

尝试:

$time = round(time() / 300) * 300;
于 2012-04-14T00:03:17.057 回答
11

试试这个功能:

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
于 2014-09-29T15:05:32.133 回答
2

对于使用Carbon的人(例如使用 Laravel 的人),这可以帮助:

/**
 * 
 * @param \Carbon\Carbon $now
 * @param int $nearestMin
 * @param int $minimumMinutes
 * @return \Carbon\Carbon
 */
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));
}
于 2019-06-05T20:48:48.977 回答
0

对于使用

Carbon::createFromTimestamp(round(time() / 300) * 300)
于 2021-07-29T04:55:13.000 回答