PHP DateTime round up to nearest 10 minutes

I stumbled upon this question and wondered why all the solutions are so complicated. It's simply this:

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

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

1) Set number of seconds to 0 if necessary (by rounding up to the nearest minute)

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

2) Get minute

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

3) Convert modulo 10

$minute = $minute % 10;

4) Count minutes to next 10-multiple minutes if necessary

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

Edited, thanks @Ondrej Henek and @berturion

Tags:

Datetime

Php