﻿ How to Round Up the Time to the Nearest X Minutes - ITCodar

# How to Round Up the Time to the Nearest X Minutes

## How can I round up the time to the nearest X minutes?

DateTime RoundUp(DateTime dt, TimeSpan d)
{
return new DateTime((dt.Ticks + d.Ticks - 1) / d.Ticks * d.Ticks, dt.Kind);
}

Example:

var dt1 = RoundUp(DateTime.Parse("2011-08-11 16:59"), TimeSpan.FromMinutes(15));
// dt1 == {11/08/2011 17:00:00}

var dt2 = RoundUp(DateTime.Parse("2011-08-11 17:00"), TimeSpan.FromMinutes(15));
// dt2 == {11/08/2011 17:00:00}

var dt3 = RoundUp(DateTime.Parse("2011-08-11 17:01"), TimeSpan.FromMinutes(15));
// dt3 == {11/08/2011 17:15:00}

## 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)

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;
}

Edited, thanks @Ondrej Henek and @berturion

## How do I round a column of time data to the nearest 15 minutes in r?

Here an approach with lubridate. We first generate an arbitrary data set and then round it to 15minutes:

library(lubridate)
x <- seq(as.POSIXct("2021-05-19 10:00"), as.POSIXct("2021-05-19 11:00"), 240)
x

round_date(x, unit="15 mins")

Edit: here the same idea with minutes only. We use a fake date, append the time, round it to 15min and extract minutes only:

library(lubridate)
x <- c("0:03", "0:18", "0:33", "0:48")
format(round_date(as.POSIXct(paste("1900-01-01 ", x)), unit="15 mins"), "%M")

## How to round to nearest X minutes with PL/pgSQL?

_minutes * interval '1 minute'

you should be subtracting

(_minutes % _nearest) * interval '1 minute'

(_nearest - (_minutes % _nearest)) * interval '1 minute'

## How to round to nearest hour and minutes by incremment in JavaScript without using moment.js?

You could take all minutes and divide by 15 for getting the whole quarter and multiply by 15 for the result. Then take hours and minutes and apply formatting. Return joined values.

function roundMinutes(t) {    function format(v) { return v < 10 ? '0' + v: v; }
var m = t.split(':').reduce(function (h, m) { return h * 60 + +m; }); m = Math.ceil(m / 15) * 15; return [Math.floor(m / 60), m % 60].map(format).join(':');}
var data = ['10:00', '10:13', '10:15', '10:16', '16:00', '16:12', '16:55'];
console.log(data.map(roundMinutes));

## DateTime Round Up and Down

case RoundingDirection.Up:
t = dt.AddMinutes((60 - dt.Minute) % 10);
case RoundingDirection.Down:

Demo: http://ideone.com/AlB7Q

## Round a Date() to the nearest 5 minutes in javascript

That's pretty simple if you already have a Date object:

var coeff = 1000 * 60 * 5;
var date = new Date(); //or use any other date
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff)