C# DateTime extensions that rounds a date time value Up, Down or to the Nearest minutes. Smaller units are zeroed out.
Example, round down to nearest 15 minutes.
RoundToNearestMinuteProper(15, RoundingDirection.Down)
Example, round down to nearest 15 minutes.
RoundToNearestMinuteProper(15, RoundingDirection.Down)
Test code and used in my Solo SCRUM Sprinter App - book work effort in Outlook calendar directly every 30mins automatically.
AI CoPilot Improved Code or is it? Added March 17, 2025
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)); } } |
Optimizations: 1/2 of a number use right-shift
int half = number >> 1; // Right-shift by 1 to divide by 2


No comments:
Post a Comment