Wednesday, October 10, 2018

C# Round Datetime Extension To Nearest Minute And Smaller Units Are Rounded To Zero



C# D
ateTime extensions that rounds a datetime Up, Down or Nearest minutes and smaller units are rounded to zero.




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
     
public static class Program
{
 /// <summary>
 /// Rounds datetime up, down or to nearest minutes and all smaller units to zero
 /// </summary>
 /// <param name="dt">ignore, implicitly passed</param>
 /// <param name="rndmin">mins to round to</param>
 /// <param name="directn">Up,Down,Nearest</param>
 /// <returns>rounded datetime with all smaller units than mins rounded off</returns>
 public static DateTime RoundToNearestMinuteProper(this DateTime dt, int rndmin, RoundingDirection directn)
 {
   if (rndmin == 0) //can be > 60 mins
   return dt;
  
   TimeSpan d = TimeSpan.FromMinutes(rndmin); //this can be passed as a parameter, or use any timespan unit FromDays, FromHours, etc.  
  
   long delta = 0;
   Int64 modTicks = dt.Ticks % d.Ticks;
  
   switch (directn)
   {
    case RoundingDirection.Up:
       delta = (modTicks != 0) ? d.Ticks - modTicks : 0;
    break;
    case RoundingDirection.Down:
       delta = -modTicks; 
    break;
    case RoundingDirection.Nearest:
    {
       bool roundUp = modTicks > (d.Ticks / 2);
       var offset = roundUp ? d.Ticks : 0;
       delta = offset - modTicks; 
       break;
    }
   
   }
   return new DateTime(dt.Ticks + delta, dt.Kind); 
 }
 
 public enum RoundingDirection
 {
  Up,
  Down,
  Nearest
 }
 
 public static void Main()
 {
  //var dt = new DateTime(2001, 1, 1, 0, 0, 0, 000);
  //var dt = new DateTime(2018, 08, 03, 10, 7, 30, 000); //8/3/2018 10:00:00 AM Nearest, re 15/2 = 7.5 mins or 7 mins and 30 secs
  var dt = new DateTime(2018, 08, 03, 10, 7, 31, 000); //8/3/2018 10:15:00 AM Nearest
  
  Console.WriteLine(dt.RoundToNearestMinuteProper(15, RoundingDirection.Up)); 
  Console.WriteLine(dt.RoundToNearestMinuteProper(15, RoundingDirection.Down)); 
  Console.WriteLine(dt.RoundToNearestMinuteProper(15, RoundingDirection.Nearest)); 
 }
}

No comments:

Post a Comment