PHP Datetime Round Up to Nearest 10 Minutes

PHP DateTime round up to nearest 10 minutes

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

PHP round datetime to nearest 5 interval

Thanks to this post https://stackoverflow.com/a/26103014/3481654

The formula for that is

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

In complete working code

function nearest5Mins($time) {
$time = (round(strtotime($time) / 300)) * 300;
return date('Y-M-d H:i', $time);
}
echo nearest5Mins('11/14/2017 22:48');
echo "<br>";
echo nearest5Mins('11/14/2017 11:23');

DEMO

Round minute down to nearest quarter hour

Your full function would be something like this...

function roundToQuarterHour($timestring) {
$minutes = date('i', strtotime($timestring));
return $minutes - ($minutes % 15);
}

Round datetime to last hour

Try this,

$date = "2013-04-20 16:25:34"; 
echo date("Y-m-d H:00:00",strtotime($date));

CodePad Demo.

Round up current time to nearest 15 minutes using PHP

here is your answer

$current_date = date('d-M-Y g:i:s A');
echo $current_date."<br/>";
$current_time = strtotime($current_date);

$frac = 900;
$r = $current_time % $frac;

$new_time = $current_time + ($frac-$r);
$new_date = date('d-M-Y g:i:s A', $new_time);

echo $new_date."<br/>";

LIVE DEMO

Round php timestamp to the nearest minute

If the timestamp is a Unix style timestamp, simply

$rounded = round($time/60)*60;

If it is the style you indicated, you can simply convert it to a Unix style timestamp and back

$rounded = date('H:i:s', round(strtotime('16:45:34')/60)*60);

round() is used as a simple way of ensuring it rounds to x for values between x - 0.5 <= x < x + 0.5. If you always wanted to always round down (like indicated) you could use floor() or the modulo function

$rounded = floor($time/60)*60;
//or
$rounded = time() - time() % 60;

Round time string in gap of 30 minutes

You should try this: This will round it to the nearest half an hour.

Use ceil function.

<?php

$rounded = date('H:i:s', ceil(strtotime('16:20:34')/1800)*1800);
echo $rounded;

?>

Output: 16:30:00

http://codepad.org/4WwNO5Rt

PHP round time() up (future) to next multiple of 5 minutes

 $now = time();     
$next_five = ceil($now/300)*300;

This will give you the next round five minutes (always greater or equal the current time).

I think that this is what you need, based on your description.



Related Topics



Leave a reply



Submit