c# datetime round to nearest 15 minutes code example

Example: c# round datetime

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));
}