Here is a methods that I use to round DateTime class to the next minute interval.
public static DateTime RoundDateToMinuteInterval(this DateTime time, int minuteInterval, RoundingDirection direction = RoundingDirection.RoundUp)
{
if (minuteInterval == 0)
return time;
decimal interval = (decimal)minuteInterval;
decimal actMinute = (decimal)time.Minute;
if (actMinute == 0.00M)
return time;
int newMinutes = 0;
switch (direction)
{
case RoundingDirection.Round:
newMinutes = (int)(Math.Round(actMinute / interval, 0) * interval);
break;
case RoundingDirection.RoundDown:
newMinutes = (int)(Math.Truncate(actMinute / interval) * interval);
break;
case RoundingDirection.RoundUp:
newMinutes = (int)(Math.Ceiling(actMinute / interval) * interval);
break;
}
time = time.AddMinutes(time.Minute * -1);
time = time.AddSeconds(time.Second * -1);
time = time.AddMilliseconds(time.Millisecond * -1);
return time.AddMinutes(newMinutes);
}
public enum RoundingDirection
{
RoundUp,
RoundDown,
Round
}
If you have a DateTime that is:
DateTime d = new DateTime(2011, 4, 19, 10, 20, 0);
DateTime roundUpDateTime.RoundDateToMinuteInterval(15);