13,198,563 members (50,670 online)
alternative version

#### Stats

35.6K views
22 bookmarked
Posted 23 Mar 2008

# Rounding a DateTime object to a defined number of minutes

, 23 Mar 2008
 Rate this:
A simple two line function to round a DateTime up, down, or to a nearest defined number of minutes.

## Introduction

Rounding a `DateTime` up (or down) to the nearest number of minutes seems a simple requirement, but is surprisingly unintuitive due to the relationships and different properties of `DateTime` and `TimeSpan` classes.

I've come across some pretty dreadful examples on the web, so thought I'd post a much simpler (and faster) one.

## Using the code

This function accepts the number of minutes to be rounded to.

```public enum eRoundingDirection { up, down, nearest }

public DateTime RoundDateTime(DateTime dt, int minutes, eRoundingDirection direction)

{
TimeSpan t;

switch (direction)
{
case eRoundingDirection.up:
t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes, 0)); break;
case eRoundingDirection.down:
t = (dt.Subtract(DateTime.MinValue)); break;
default:
t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes / 2, 0)); break;
}

(((int)t.TotalMinutes) / minutes) * minutes, 0));
}```

## Points of interest

Why use "default:" instead of "nearest"? Simply because it saves defining a default value for the `TimeSpan`.

Integer math helps keep this function speedy, and avoids those tricky rounding errors in the milliseconds.

## About the Author

 CEO QuestMetrics Australia
No Biography provided

## Comments and Discussions

 First Prev Next
 So so Luc Pattyn6-Mar-10 9:30 Luc Pattyn 6-Mar-10 9:30
 Excellent code! Kebrite6-Feb-10 22:17 Kebrite 6-Feb-10 22:17
 Re: Excellent code! Jason Sobell7-Feb-10 1:19 Jason Sobell 7-Feb-10 1:19
 Very Interesting merlin98124-Mar-08 4:28 merlin981 24-Mar-08 4:28
 Last Visit: 31-Dec-99 18:00     Last Update: 21-Oct-17 17:11 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.