PHP将时间()上升(未来)到下一个5分钟的倍数

时间:2012-04-13 23:59:58

标签: php time rounding

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

5 个答案:

答案 0 :(得分:34)

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

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

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

答案 1 :(得分:14)

尝试:

$time = round(time() / 300) * 300;

答案 2 :(得分:6)

尝试此功能:

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

答案 3 :(得分:0)

对于使用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));
}

答案 4 :(得分:0)

使用Carbon

Carbon::createFromTimestamp(round(time() / 300) * 300)