PHP DateTime四舍五入到最近的10分钟

时间:2013-11-06 14:16:25

标签: php datetime

我正在从mysql字段中检索日期时间,但我需要将其向上舍入到最接近的10分钟。

例如,如果日期时间是2013-11-06 14:00:01,我想将时间返回到2013年6月6日14:10。

最简单的方法是什么?

$datetime = new DateTime($mysqldata);

echo $datetime->format('d/m/Y G:i');

任何建议表示赞赏。

感谢。

10 个答案:

答案 0 :(得分:16)

1)如有必要,将秒数设置为0(通过四舍五入到最接近的分钟)

$second = $datetime->format("s");
if($second > 0)
    $datetime->add(new DateInterval("PT".(60-$second)."S"));

2)得到分钟

$minute = $datetime->format("i");

3)转换模10

$minute = $minute % 10;

4)如有必要,将分钟计数到下一个10分钟

if($minute != 0)
{
    // Count difference
    $diff = 10 - $minute;
    // Add difference
    $datetime->add(new DateInterval("PT".$diff."M"));
}

编辑,感谢@Ondrej Henek和@berturion

答案 1 :(得分:13)

@rand的答案有一个错误,当我们要舍入的DateTime已经是10分钟的倍数。它将在10分钟后跳到不想要的地方。

此外,当秒数为零时,不希望始终使用($datetime->add(new \DateInterval("PT".(60-$second)."S"));跳到下一分钟。

此增强功能修复了这些错误,并采用$ precision参数来覆盖更多用例。

function roundTime(\DateTime $datetime, $precision = 30) {
    // 1) Set number of seconds to 0 (by rounding up to the nearest minute if necessary)
    $second = (int) $datetime->format("s");
    if ($second > 30) {
        // Jumps to the next minute
        $datetime->add(new \DateInterval("PT".(60-$second)."S"));
    } elseif ($second > 0) {
        // Back to 0 seconds on current minute
        $datetime->sub(new \DateInterval("PT".$second."S"));
    }
    // 2) Get minute
    $minute = (int) $datetime->format("i");
    // 3) Convert modulo $precision
    $minute = $minute % $precision;
    if ($minute > 0) {
        // 4) Count minutes to next $precision-multiple minutes
        $diff = $precision - $minute;
        // 5) Add the difference to the original date time
        $datetime->add(new \DateInterval("PT".$diff."M"));
    }
}

此功能现在非常适合我的使用,也可能适用于其他人。

答案 2 :(得分:6)

您可以使用ceil,floor和round函数将DateTime向上,向下或最近的分钟间隔舍入,如下所示:

/**
 * @param \DateTime $dateTime
 * @param int $minuteInterval
 * @return \DateTime
 */
public function roundUpToMinuteInterval(\DateTime $dateTime, $minuteInterval = 10)
{
    return $dateTime->setTime(
        $dateTime->format('H'),
        ceil($dateTime->format('i') / $minuteInterval) * $minuteInterval,
        0
    );
}

/**
 * @param \DateTime $dateTime
 * @param int $minuteInterval
 * @return \DateTime
 */
public function roundDownToMinuteInterval(\DateTime $dateTime, $minuteInterval = 10)
{
    return $dateTime->setTime(
        $dateTime->format('H'),
        floor($dateTime->format('i') / $minuteInterval) * $minuteInterval,
        0
    );
}

/**
 * @param \DateTime $dateTime
 * @param int $minuteInterval
 * @return \DateTime
 */
public function roundToNearestMinuteInterval(\DateTime $dateTime, $minuteInterval = 10)
{
    return $dateTime->setTime(
        $dateTime->format('H'),
        round($dateTime->format('i') / $minuteInterval) * $minuteInterval,
        0
    );
}

答案 3 :(得分:6)

我偶然发现了这个问题,并想知道为什么所有解决方案都如此复杂。就是这样:

function roundToNext10Min(\DateTime $dt, $precision = 10) {
    $s = $precision * 60;
    $dt->setTimestamp($s * ceil($dt->getTimestamp() / $s));
    return $dt;
}

$dt = roundToNext10Min(new DateTime($str));
echo $dt->format('d/m/Y G:i');

答案 4 :(得分:3)

我会使用时间戳:

<?php

function roundTime(\DateTime $datetime, $precision = 10) {

    $ts = $datetime->getTimestamp();
    $s = ($precision * 60);
    $remainder = $ts % $s;

    if ($remainder > 0) {
        $datetime->setTimestamp($ts + $s - $remainder);
    }

    return $datetime;
}

echo roundTime(\DateTime::createFromFormat('Y-m-d H:i:s', '2016-03-04 09:00:00'))
    ->format('Y-m-d H:i:s');
// prints: 2016-03-04 09:00:00


echo roundTime(\DateTime::createFromFormat('Y-m-d H:i:s', '2016-03-04 09:00:01'))
    ->format('Y-m-d H:i:s');
// prints: 2016-03-04 09:10:00

答案 5 :(得分:1)

public function roundupMinutesFromDatetime(\Datetime $date, $minuteOff = 10)
{
    $string = sprintf(
         "%d minutes %d seconds", 
         $date->format("i") % $minuteOff, 
         $date->format("s")
    );

    return  $date->sub(\DateInterval::createFromDateString($string));
}

测试:

public function datetimeProvider()
{
    return array(
        array('2015-01-01 15:16:17', '2015-01-01 15:10:00'),
        array('2015-01-01 09:59:39', '2015-01-01 09:50:00'),
    );
}

/**
 * @dataProvider datetimeProvider
 */
public function testRoundupToMinutesFromDatetime($dateStr, $dateStrAssert)
{
    $format = 'Y-m-d H:i:s';

    $date = \DateTime::createFromFormat($format, $dateStr);
    $date = $this->repo->roundupMinutesFromDatetime($date);
    $this->assertEquals($dateStrAssert, $date->format('Y-m-d H:i:s'));
}

玩得开心。

答案 6 :(得分:0)

您需要使用strtotime()函数将日期转换为时间戳,然后添加或删除分钟,例如

<?php
$datenow  = date("Y-m-d H:i:s", time());
$maketime = strtotime($datenow );

$minutes     = 10;

$after_10min = date("Y-m-d H:i:s", ( $maketime+(60*$minutes) ));
$before_10min = date("Y-m-d H:i:s", ( $maketime-(60*$minutes) ));

echo "Date now : $datenow  <br />";
echo "Date After $minutes min : $after_10min <br />";
echo "Date Before $minutes min : $before_10min <br />";
?>

答案 7 :(得分:0)

简易代码

<?php
    function next10Minutes()  {
        $time = time() + 600;

        $nextMinutes = floor(date("i", $time) / 10) * 10;

        if ($nextMinutes < 10) {
            $nextMinutes = "00";
        }

        return strtotime(date("d-m-Y H:{$nextMinutes}:00", $time));
    }

答案 8 :(得分:0)

这是一个可将(四舍五入,向上,向下或仅四舍五入)四舍五入为秒,分钟或小时的函数。受@esqilin 's answer

的启发

许多博特兰人死了,都是为了带给你这些信息。

PHP 7,尽管可能不难调整为5。

/**
 * Round $datetime to nearest <$precision> <$unit>s - e.g nearest 10 seconds -- or always up/down per $calc
 * @param \DateTimeInterface $datetime
 * @param int    $precision Round to the nearest number of {$unit}s
 * @param string $unit      'h', 'm', or 's' for Hours, Minutes, or Seconds; or PHP's 'G'/'H' (hours) or 'i' (minutes)
 * @param int    $calc      -1, 0, or 1 = floor, round, or ceiling calculations
 * @return \DateTimeInterface
 * @throws \Exception
 */
function roundTime( \DateTimeInterface $datetime, int $precision = 1, string $unit = 's', int $calc = 0 ) :\DateTimeInterface {
    $offset = $datetime->format( 'Z' );
    $datetime = ( clone $datetime )->modify( "+$offset seconds" );
    switch( $unit ) {   // convert human readable units to PHP DateTime format string
        case 'h':
        case 'H':
            $unit = 'G';
            break;
        case 'm':
            $unit = 'i';
            break;
        // 's' -> 's', no change
    }
    $secs = [ 'G'=>3600, 'i'=>60, 's'=>1 ]; // seconds per hour/minute/second
    if( ! in_array( $unit, array_keys( $secs ) ) ) {
        trigger_error( "Unknown \$unit parameter '$unit' in " . __FUNCTION__ . ". Recognized formats are 'h', 'm', 's', (hours/minutes/seconds), or PHP's 'G', 'H', or 'i'" );
        return $datetime;
    }
    $precision = $precision * $secs[$unit];
    if( -1 === $calc ) {
        $round = 0;
    } elseif( 1 === $calc ) {
        $round = $precision;
    } elseif( 1 == $precision && 's' == $unit ) { // in this -- and only this -- case, we need partial seconds
        $round = ( (int) $datetime->format('v') ) >= 500 ? 1 : 0;
    } else {
        $round = ( ( (int) $datetime->format('U') ) % $precision >= ( $precision/2 ) ) ? $precision : 0;
    }
    $result = $datetime->setTimestamp( ( $precision * floor( $datetime->format('U') / $precision ) ) + $round - $offset );
    return $result;
}

在问题中建议的情况下,您将使用:

$datetime = new DateTime($mysqldata);

echo roundTime( $datetime, 10, 'm', 1 );

答案 9 :(得分:-1)

我重载了这个类并创建了一个方法:

class MyWish_DateTime extends DateTime {

public function formatToNearRangeMinutesSql($range) {
        $midleRange = $range / 2;

        $minutes = self::format("i");
        $modulo = $minutes % $range;
        if ($modulo > $midleRange) {
            $this->addMinutes($range - $modulo);
        }
        else {
            $this->addMinutes(-$modulo);
        }
        return self::format("H:i");
    }
}