Click here to Skip to main content
12,547,501 members (53,818 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


22 bookmarked

Rounding a DateTime object to a defined number of minutes

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


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;
      t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes / 2, 0)); break;

  return DateTime.MinValue.Add(new TimeSpan(0, 
         (((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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jason Sobell
CEO QuestMetrics
Australia Australia
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralSo so Pin
Luc Pattyn6-Mar-10 9:30
mvpLuc Pattyn6-Mar-10 9:30 
GeneralExcellent code! Pin
Kebrite6-Feb-10 22:17
memberKebrite6-Feb-10 22:17 
GeneralRe: Excellent code! Pin
Jason Sobell7-Feb-10 1:19
memberJason Sobell7-Feb-10 1:19 
GeneralVery Interesting Pin
merlin98124-Mar-08 4:28
membermerlin98124-Mar-08 4:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161018.1 | Last Updated 23 Mar 2008
Article Copyright 2008 by Jason Sobell
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid