PHP 将 time() 向上(未来)向上舍入 5 分钟的倍数

问题描述 投票:0回答:6

如何将

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

php time rounding
6个回答
48
投票
 $now = time();     
 $next_five = ceil($now/300)*300;

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

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


17
投票

尝试:

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

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

3
投票

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

2
投票

对于使用

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

0
投票

我将其留在这里,因为也许有人正在寻找相同的解决方案。 将实际碳时间四舍五入到接下来的 5 分钟比我想象的要复杂。

这是我的解决方案:

private function currentTimeRoundedUpToNext5Minutes($time = null): Carbon
{
    $now = $time ? Carbon::parse($time) : Carbon::now();

    // If the actual minute is divisible by 5 we want to add 5 minutes
    if ($now->minute % 5 == 0) {
        $now->minute += 5;
        $now->second(0);

        return $now;
    }

    // If it's not divisible by 5 we need to round up to next 5 minutes
    $roundedMinute = ceil($now->minute / 5) * 5;

    // If rounded minute is equal or greater than 60 - add an hour and set minutes to 0
    if ($roundedMinute >= 60) {
        $now->addHour();
        $now->minute = 0;
    } else {
        $now->minute = $roundedMinute;
    }

    $now->second(0);

    return $now;
}
© www.soinside.com 2019 - 2024. All rights reserved.