DateTime Round Up and Down

Here is a fast way to truncate (round down)

var now = DateTime.Now;
var nowTicks = now.Ticks;

//removing the nanoseconds, miliseconds, and seconds from the nowTicks
var lastMinute = new DateTime(nowTicks - (nowTicks % (1000*1000*10*60)));

This will let you round according to any interval given.

public static class DateTimeExtensions
{
  public static DateTime Floor(this DateTime dateTime, TimeSpan interval)
  {
    return dateTime.AddTicks(-(dateTime.Ticks % interval.Ticks));
  }

  public static DateTime Ceiling(this DateTime dateTime, TimeSpan interval)
  {
    var overflow = dateTime.Ticks % interval.Ticks;

    return overflow == 0 ? dateTime : dateTime.AddTicks(interval.Ticks - overflow);
  }

  public static DateTime Round(this DateTime dateTime, TimeSpan interval)
  {
    var halfIntervalTicks = (interval.Ticks + 1) >> 1;

    return dateTime.AddTicks(halfIntervalTicks - ((dateTime.Ticks + halfIntervalTicks) % interval.Ticks));
  }
}

To take care of truncating the seconds, I would simply subtract the seconds and milliseconds from the date-time before sending them into the rounding functions.


How about:

case RoundingDirection.Up:
    t = dt.AddMinutes((60 - dt.Minute) % 10);
case RoundingDirection.Down:
    t = dt.AddMinutes(-dt.Minute % 10);

Demo: http://ideone.com/AlB7Q