Search code examples
c#.netdatetimerounding

DateTime Round Up and Down


Ive been looking for a proper rounding mechanism but nothing I find seems to be exactly what I need.

I need to round up and round down seperately and I also need to account for the the case when its already rounded.

I need the following rounding to happen

5:00 -> RoundDown() -> 5:00
5:04 -> RoundDown() -> 5:00
5:09 -> RoundDown() -> 5:00
5:10 -> RoundDown() -> 5:10

4:00 -> RoundUp() -> 4:00
4:50 -> RoundUp() -> 4:50
4:51 -> RoundUp() -> 5:00
4:56 -> RoundUp() -> 5:00 

Basically I need it to RoundUp() or RoundDown() to the nearest 10 minutes explicitly but it should also leave time untouched if it already is in a multiple of 10 minutes. Also I'd like to truncate any seconds to that they have no effect on the rounding procedure

4:50:45 -> 4:50:00 -> RoundUp() -> 4:50

Does anyone have any handy code to accomplish this.

I found this code somewhere but it rounds 5:00 -> RoundUp() -> 5:10 rather than leaving it intact because its already a multiple of 10 and needs no rounding. Also Im not sure how seconds would effect it

public static DateTime RoundDateTime(this DateTime dt, int minutes, RoundingDirection direction)
{
    TimeSpan t;
    switch (direction)
    {
        case RoundingDirection.Up:
            t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes, 0)); break;
        case RoundingDirection.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));
}

Hope someone can edit that method to make it work for me. Thanks


Solution

  • How about:

    case RoundingDirection.Up:
        t = dt.AddMinutes((60 - dt.Minute) % 10);
    case RoundingDirection.Down:
        t = dt.AddMinutes(-dt.Minute % 10);
    

    Demo: http://ideone.com/AlB7Q