title: Rounding DateTime objects
body: <p>I want to round dates/times to the nearest interval for a charting application. I'd like an extension method signature like follows so that the rounding can be acheived for any level of accuracy:</p>
  
  <pre><code>static DateTime Round(this DateTime date, TimeSpan span);
  </code></pre>
  
  <p>The idea is that if I pass in a timespan of ten minutes, it will round to the nearest ten minute interval. I can't get my head around the implementation and am hoping one of you will have written or used something similar before.</p>
  
  <p>I think either a floor, ceiling or nearest implementation is fine.</p>
  
  <p>Any ideas?</p>
  
  <p>Edit:  Thanks to @tvanfosson &amp; @ShuggyCoUk, the implementation looks like this:</p>
  
  <pre><code>public static class DateExtensions {
      public static DateTime Round(this DateTime date, TimeSpan span) {
          long ticks = (date.Ticks + (span.Ticks / 2) + 1)/ span.Ticks;
          return new DateTime(ticks * span.Ticks);
      }
      public static DateTime Floor(this DateTime date, TimeSpan span) {
          long ticks = (date.Ticks / span.Ticks);
          return new DateTime(ticks * span.Ticks);
      }
      public static DateTime Ceil(this DateTime date, TimeSpan span) {
          long ticks = (date.Ticks + span.Ticks - 1) / span.Ticks;
          return new DateTime(ticks * span.Ticks);
      }
  }
  </code></pre>
  
  <p>And is called like so:</p>
  
  <pre><code>DateTime nearestHour = DateTime.Now.Round(new TimeSpan(1,0,0));
  DateTime minuteCeiling = DateTime.Now.Ceil(new TimeSpan(0,1,0));
  DateTime weekFloor = DateTime.Now.Floor(new TimeSpan(7,0,0,0));
  ...
  </code></pre>
  
  <p>Cheers!</p>