(抱歉,复活了;我知道这是一个古老且已回答的问题 - 只是为了 Google 的缘故添加了一些额外的代码。)
我从JayMcClellan's answer 开始,但后来我希望它更通用,四舍五入到任意间隔(不仅仅是 5 秒)。因此,我最终将 Jay 的方法留给了在刻度上使用 Math.Round 的方法,并将其放入可以采用任意间隔的扩展方法中,并且还提供了更改舍入逻辑的选项(银行家的舍入与远离零的舍入)。我在这里发帖以防这对其他人也有帮助:
public static TimeSpan Round(this TimeSpan time, TimeSpan roundingInterval, MidpointRounding roundingType) {
return new TimeSpan(
Convert.ToInt64(Math.Round(
time.Ticks / (decimal)roundingInterval.Ticks,
roundingType
)) * roundingInterval.Ticks
);
}
public static TimeSpan Round(this TimeSpan time, TimeSpan roundingInterval) {
return Round(time, roundingInterval, MidpointRounding.ToEven);
}
public static DateTime Round(this DateTime datetime, TimeSpan roundingInterval) {
return new DateTime((datetime - DateTime.MinValue).Round(roundingInterval).Ticks);
}
它不会因为简单的效率而赢得任何奖项,但我发现它易于阅读且使用直观。示例用法:
new DateTime(2010, 11, 4, 10, 28, 27).Round(TimeSpan.FromMinutes(1)); // rounds to 2010.11.04 10:28:00
new DateTime(2010, 11, 4, 13, 28, 27).Round(TimeSpan.FromDays(1)); // rounds to 2010.11.05 00:00
new TimeSpan(0, 2, 26).Round(TimeSpan.FromSeconds(5)); // rounds to 00:02:25
new TimeSpan(3, 34, 0).Round(TimeSpan.FromMinutes(37); // rounds to 03:42:00...for all your round-to-37-minute needs