开发者

Round UP c# TimeSpan to 5 minutes [duplicate]

This question already has answers here: Closed 11 years ago.

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);
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜