How to deal with Rounding-Off TimeSpan?

I take the difference between the two DateTime fields and save them in a TimeSpan variable. Now I need to round TimeSpan with the following rules:

if the minutes in TimeSpan are less than 30, then the minutes and seconds should be set to zero. If the minutes in TimeSpan are equal to or greater than 30, then the hours should be increased by 1, and the minutes and seconds should be set to zero.

TimeSpan can also be a negative value, so in this case I need to keep the sign.

I could fulfill the requirement if TimeSpan was not a negative value, although I wrote code that I do not like with its inefficiency, since it is more cumbersome.

Please suggest me a simpler and more efficient method.

Respectfully,

This is my code that works great when TimeSpan is not a negative value.

TimeSpan time_span = endTime.Subtract(startTime); TimeSpan time_span1; if (time_span.Minutes >= 30) { time_span1 = new TimeSpan(time_span.Hours + 1, 0, 0); } else { time_span1 = new TimeSpan(time_span.Hours, 0, 0); } 

time_span1 will contain the result.

+5
source share
3 answers

What about:

 public static TimeSpan Round(TimeSpan input) { if (input < TimeSpan.Zero) { return -Round(-input); } int hours = (int) input.TotalHours; if (input.Minutes >= 30) { hours++; } return TimeSpan.FromHours(hours); } 
+9
source

you can use

 double v = span.TotalHours; v = Math.Round(v, MidpointRounding.AwayFromZero); span = TimeSpan.FromHours(v); 

It depends on whether I correctly understood your rules for negative values.

+4
source

TimeSpan is unchanged, so you need to create a new one. This is also a great example of using extension methods in C #:

 public static class TimeSpanUtility { public static TimeSpan Round( this TimeSpan ts ) { var sign = ts < TimeSpan.Zero ? -1 : 1; var roundBy = Math.Abs(ts.Minutes) >= 30 ? 1 : 0; return TimeSpan.FromHours( ts.TotalHours + (sign * roundBy) ); } } // usage would be: var someTimeSpan = new TimeSpan( 2, 45, 15 ); var roundedTime = someTimeSpan.Round(); 
+3
source

Source: https://habr.com/ru/post/886158/


All Articles