PHP round time() up (future) to next multiple of 5 minutes

眉间皱痕 提交于 2019-12-18 22:34:19

问题


How do I round the result of time() up (towards the future) to the next multiple of 5 minutes?


回答1:


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

This will give you the next round five minutes (always greater or equal the current time).

I think that this is what you need, based on your description.




回答2:


Try:

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



回答3:


Try this function:

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



回答4:


For people using Carbon (such as people using Laravel), this can help:

/**
 * 
 * @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();
}

These test assertions pass:

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));
}


来源:https://stackoverflow.com/questions/10149792/php-round-time-up-future-to-next-multiple-of-5-minutes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!