Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Extension Methods in C#

, 18 Apr 2011
Rate this:
Please Sign up or sign in to vote.
Here is a methods that I use to round DateTime class to the next minute interval./// /// Rounds a date value to a given minute interval/// /// Original time value/// Number of minutes to round up or down...
Here is a methods that I use to round DateTime class to the next minute interval.
/// <summary>
/// Rounds a date value to a given minute interval
/// </summary>
/// <param name="time">Original time value</param>
/// <param name="minuteInterval">Number of minutes to round up or down to</param>
/// <returns></returns>
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;
  }
 
  // *** strip time
  time = time.AddMinutes(time.Minute * -1);
  time = time.AddSeconds(time.Second * -1);
  time = time.AddMilliseconds(time.Millisecond * -1);
 
  // *** add new minutes back on
  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);
// And you call the function as this.
DateTime roundUpDateTime.RoundDateToMinuteInterval(15);
// roundUpDateTime will be - 2011-04-19 10:30:00

License

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

About the Author

Kim Togo
Software Developer Miralix
Denmark Denmark
Has worked as a programmer since 1999, starting with C++/MFC, Java, PHP and MySQL. Now it is all about C# (my favorite programming language), MS SQL, Azure and Xamarin (iOS/Android/WP8)
 
My primary work is to create applications that interacts with PABC/PBX, Microsoft Lync / UCMA.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 19 Apr 2011
Article Copyright 2011 by Kim Togo
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid