Round UP c# TimeSpan to 5 minutes [duplicate]
Possible Duplicate:
How to deal with Rounding-off TimeSpan?
Is there a way to easily round a c# TimeSpan (possible c开发者_Python百科ontaining more than one day) up so that
0 days 23h 59m becomes 1 days 0 h 0 m?
0 days 23h 47m becomes 0 days 23 h 50 m?
etc?
Here's what i've 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 rather simple:( Isn't there some kind of built in c# function I can use to round timespans?
Here it 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);
static TimeSpan RoundTimeSpan(TimeSpan value)
{
return TimeSpan.FromMinutes(System.Math.Ceiling(value.TotalMinutes / 5) * 5);
}
精彩评论