This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

C# round up time to nearest X minutes

By: a guest on Apr 4th, 2012  |  syntax: None  |  size: 1.94 KB  |  views: 158  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. DateTime RoundUp(DateTime dt, TimeSpan d)
  2. {
  3.     return new DateTime(((dt.Ticks + d.Ticks - 1) / d.Ticks) * d.Ticks);
  4. }
  5.        
  6. var dt1 = RoundUp(DateTime.Parse("2011-08-11 16:59"), TimeSpan.FromMinutes(15));
  7. // dt1 == {11/08/2011 17:00:00}
  8.  
  9. var dt2 = RoundUp(DateTime.Parse("2011-08-11 17:00"), TimeSpan.FromMinutes(15));
  10. // dt2 == {11/08/2011 17:00:00}
  11.  
  12. var dt3 = RoundUp(DateTime.Parse("2011-08-11 17:01"), TimeSpan.FromMinutes(15));
  13. // dt3 == {11/08/2011 17:15:00}
  14.        
  15. void Main()
  16. {
  17.     var date1 = new DateTime(2011, 8, 11, 16, 59, 00);
  18.     date1.Round15().Dump();
  19.  
  20.     var date2 = new DateTime(2011, 8, 11, 17, 00, 02);
  21.     date2.Round15().Dump();
  22.  
  23.     var date3 = new DateTime(2011, 8, 11, 17, 01, 23);
  24.     date3.Round15().Dump();
  25.  
  26.     var date4 = new DateTime(2011, 8, 11, 17, 00, 00);
  27.     date4.Round15().Dump();
  28. }
  29.  
  30. public static class Extentions
  31. {
  32.     public static DateTime Round15(this DateTime value)
  33.     {  
  34.         var ticksIn15Mins = TimeSpan.FromMinutes(15).Ticks;
  35.  
  36.         return (value.Ticks % ticksIn15Mins == 0) ? value : new DateTime((value.Ticks / ticksIn15Mins + 1) * ticksIn15Mins);
  37.     }
  38. }
  39.        
  40. 8/11/2011 5:00:00 PM
  41. 8/11/2011 5:15:00 PM
  42. 8/11/2011 5:15:00 PM
  43. 8/11/2011 5:00:00 PM
  44.        
  45. dt.AddSeconds(900 - (x.Minute * 60 + x.Second) % 900)
  46.        
  47. public static class DateTimeExtensions
  48. {
  49.  
  50.     public static DateTime Round( this DateTime value , TimeSpan unit )
  51.     {
  52.         return Round( value , unit , default(MidpointRounding) ) ;
  53.     }
  54.  
  55.     public static DateTime Round( this DateTime value , TimeSpan unit , MidpointRounding style )
  56.     {
  57.         if ( unit <= TimeSpan.Zero ) throw new ArgumentOutOfRangeException("unit" , "value must be positive") ;
  58.  
  59.         Decimal  units        = (decimal) value.Ticks / (decimal) unit.Ticks ;
  60.         Decimal  roundedUnits = Math.Round( units , style ) ;
  61.         long     roundedTicks = (long) roundedUnits * unit.Ticks ;
  62.         DateTime instance     = new DateTime( roundedTicks ) ;
  63.  
  64.         return instance ;
  65.     }
  66.  
  67. }
clone this paste RAW Paste Data