Skip to content
Advertisement

PHP DateTime round up to nearest 10 minutes

I’m retrieving a datetime from a mysql field but I need to round it up to the nearest 10 minutes.

For example, If the datetime is 2013-11-06 14:00:01, I’d like to return the time as 6/11/2013 14:10.

What’s the easiest way to do this?

$datetime = new DateTime($mysqldata);

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

Any advice appreciated.

Thanks.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement