Introduce DataBase,Asp.net,JavaScript,Xml,Html,Css,Sql,Php,ASP.NET Controls,AJAX,Tools,HTML,CSS,JavaScript,Open Source Project,WPF,.Net Framework,Linq
Top Recommended Hosting

Rounding a DateTime object to a defined number of minutes

by the3factory 3/23/2008 10:41:00 PM

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;
}
return DateTime.MinValue.Add(new TimeSpan(0, (((int)t.TotalMinutes) / minutes) * minutes, 0));
}

Related posts

Sign up for PayPal and start accepting credit card payments instantly.


Powered by BlogEngine.NET 1.2.0.0