s-a-n s-a-n - 26 days ago 10
C# Question

Roundoff Timespan to 15 min interval

I have a property in my code where users can enter a timespan in HH:mm like


10:32
10:44
15:45


I want to round off in my property to the nearest 15mins but i dont have datetime here. I only need to do it with Timespan

10:32 to 10:30
10:44 to 10:45
15:45 to 15:45
01:02 to 01:00
02:11 to 02:15
03:22 to 03:15
23:52 to 00:00


Tried all these solutions but they involve Datetime in them

How can I round up the time to the nearest X minutes?

Is there a simple function for rounding a DateTime down to the nearest 30 minutes, in C#?

DotNet Roundoff datetime to last 15 minutes

Answer

I think you want something like this:

public static class TimeSpanExtensions
{
    public static TimeSpan RoundToNearestMinutes(this TimeSpan input, int minutes)
    {
        var totalMinutes = (int)(input + new TimeSpan(0, minutes/2, 0)).TotalMinutes;

        return new TimeSpan(0, totalMinutes - totalMinutes % minutes, 0);
    }
}

If you pass in 15 as your chosen interval for rounding, the function will first add 7 mins, then round down to the nearest 15 mins. This should give you what you want.

Because the above is written an extension method, you can use it like this:

var span1 = new TimeSpan(0, 10, 37, 00).RoundToNearestMinutes(15);
var span2 = new TimeSpan(0, 10, 38, 00).RoundToNearestMinutes(15);

The first one becomes 10:30, and the second one becomes 10:45 (as desired).

Comments