Round UP C # TimeSpan up to 5 minutes

Possible duplicate:
How to deal with Rounding-off TimeSpan?

Is there a way to easily get around C # TimeSpan (possibly containing more than one day) so that

0 days 23h 59m becomes 1 day 0 h 0 m?

0 days 23h 47m becomes 0 days 23 h 50 m?

etc.?

Here is what I have come up with so far:

int remainder = span2.Minutes % 5; if (remainder != 0) { span2 = span2.Add(TimeSpan.FromMinutes(5 - remainder)); } 

it seems like a lot of code for something pretty simple :( Isn't there some kind of built-in C # function that I can use to round time slots?

+6
source share
2 answers

There he is:

 var ts = new TimeSpan(23, 47, 00); ts = TimeSpan.FromMinutes(5 * Math.Ceiling(ts.TotalMinutes / 5)); 

Or with a grain of sugar:

 public static class TimeSpanExtensions { public static TimeSpan RoundTo(this TimeSpan timeSpan, int n) { return TimeSpan.FromMinutes(n * Math.Ceiling(timeSpan.TotalMinutes / n)); } } ts = ts.RoundTo(5); 
+18
source
  static TimeSpan RoundTimeSpan(TimeSpan value) { return TimeSpan.FromMinutes(System.Math.Ceiling(value.TotalMinutes / 5) * 5); } 
+3
source

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


All Articles