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

TimS picture TimS · Aug 11, 2011 · Viewed 87.6k times · Source

Is there a simple function for rounding UP a DateTime to the nearest 15 minutes?

E.g.

2011-08-11 16:59 becomes 2011-08-11 17:00

2011-08-11 17:00 stays as 2011-08-11 17:00

2011-08-11 17:01 becomes 2011-08-11 17:15

Answer

dtb picture dtb · Aug 11, 2011
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}