2011-04-18 32 views
6

可能重复:
How to deal with Rounding-off TimeSpan?围捕C#时间跨度为5分钟

有(包含超过一天可能)一种能够方便地轮AC#时间跨度向上,以便

0天23小时59分变成1天0小时0分?

0天23小时47分变成0天23小时50分?

etc?

下面是我想出迄今:

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

这似乎是一个大量的代码的东西很简单:(是不是有某种内建在C#中的功能,我可以使用一轮时间跨度

+0

可能重复:[?如何处理四舍五入的时间跨度(http://stackoverflow.com/q/2714221/102112) – Alex 2011-04-18 15:00:26

+0

我的问题是关于围捕,而不是数学四舍五入。 – 2011-04-18 15:17:02

回答

18

这是?

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

或用糖粒:

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

谢谢你们,我居然跟着“粒糖”一起:) – 2011-04-18 15:09:47

3
static TimeSpan RoundTimeSpan(TimeSpan value) 
{ 
    return TimeSpan.FromMinutes(System.Math.Ceiling(value.TotalMinutes/5) * 5); 
}