找到最近的下一个小时

时间:2012-03-13 09:10:29

标签: php

如何在php中找到下一个最接近的小时

所以例如,如果当前时间是4:15,则下一个小时将是5,等等

$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );
echo $date->format( 'H:i:s' );

给了我来自字符串的时间,我想扩展它并获得下一个最接近的时间

11 个答案:

答案 0 :(得分:13)

$nextHour = (intval($date->format('H'))+1) % 24;
echo $nextHour; // 5

答案 1 :(得分:4)

你可以随身携带(小时,分钟,秒)并获得下一个小时吗?

$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';
$date = new DateTime( $dateString );

echo $date->format( 'H:i:s' );
echo "\n";

$nexthour = ($date->format('H') + ($date->format('i') > 0 || $date->format('s') > 0 ? 1 : 0)) % 24;
echo "$nexthour:00:00";

答案 2 :(得分:3)

<?php

$dateString = 'Tue, 13 Mar 2012 04:48:34 -0400';

$date = new DateTime( $dateString );
$date->modify('+1 hour');

echo $date->format('H:i:s').PHP_EOL;

// OR

echo date('H:i:s', strtotime($dateString) + 60 * 60).PHP_EOL;

答案 3 :(得分:2)

我刚才需要类似的东西(下一个整整一小时),我的解决方案是:

$now = time();
$nextFullHour = date(DATE_ATOM, $now + (3600 - $now % 3600));

替换3600例如60你得到下一分钟...... 如果您不需要相对于当前时间,也可以将$now替换为任何其他时间戳。

答案 4 :(得分:1)

将任何符合条件的日期()提供给:

function roundToNextHour($dateString) {
    $date = new DateTime($dateString);
    $minutes = $date->format('i');
    if ($minutes > 0) {
        $date->modify("+1 hour");
        $date->modify('-'.$minutes.' minutes');
    }
    return $date;
}

答案 5 :(得分:1)

我们走了:

<?php
echo date("H:00",strtotime($date. " + 1hour "));
?php

答案 6 :(得分:0)

尝试当前时间,如果你需要把第二个参数放到日期函数

<?php echo date('H')+1; ?>    

非常好的东西

答案 7 :(得分:0)

这是我的解决方案:

$dateTime = new \DateTime();
$dateTime->add(new \DateInterval('PT1H'))
         ->setTime($dateTime->format('H'), '00');

答案 8 :(得分:0)

还有一个:

$current_datetime = new DateTimeImmutable();
$next_full_hour_datetime = $current_datetime
    ->modify(
        sprintf(
            '+%d seconds',
            3600 - ($current_datetime->getTimestamp() % 3600)
        )
    );

答案 9 :(得分:0)

没有其他人使用过它,所以我想我会把它放到这里,这是我在上面看到的最简单的一个实际时间戳,而不仅仅是小时本身。

$now = ''; // empty uses current time, or you can insert a datetime string
$next_hour = date( 'Y-m-d H:00:00', strtotime( $now . ' +1 hour' ) );

答案 10 :(得分:0)

这次聚会有点晚了,但是这里有一个更灵活的功能,它可以将分钟间隔的dateTime对象四舍五入。您传入dateTime对象和舍入间隔(以分钟为单位),因此一个小时内,您只需传入60,以此类推。

    public function round_up_time( $datetime, $rounding_interval ) {
        // get total minutes from the start of the day
        $minutes = ( intval( $datetime->format( 'H' ) ) * 60 ) + ( intval( $datetime->format( 'i' ) ) );
        // round up the minutes based on the interval we are rounding to
        $rounded_minutes = ( intval( $minutes / $rounding_interval ) + 1 ) * $rounding_interval;
        // reset our dateTime to the very start of the day
        $datetime->setTime( 0, 0 );
        // then increase the dateTime by the rounded minutes value
        $datetime->modify( '+ ' . $rounded_minutes . ' minutes' );
    }
相关问题