DateTime上下舍入 [英] DateTime Round Up and Down
问题描述
我一直在寻找一种合适的舍入机制,但我发现似乎没有什么正是我所需要的.
Ive been looking for a proper rounding mechanism but nothing I find seems to be exactly what I need.
我需要分别向上舍入和向下舍入,并且还需要考虑已经舍入的情况.
I need to round up and round down seperately and I also need to account for the the case when its already rounded.
我需要进行以下舍入操作
I need the following rounding to happen
5:00 -> RoundDown() -> 5:00
5:04 -> RoundDown() -> 5:00
5:09 -> RoundDown() -> 5:00
5:10 -> RoundDown() -> 5:10
4:00 -> RoundUp() -> 4:00
4:50 -> RoundUp() -> 4:50
4:51 -> RoundUp() -> 5:00
4:56 -> RoundUp() -> 5:00
基本上,我需要将它显式地取到RoundUp()或RoundDown()到最近的10分钟,但是如果已经是10分钟的倍数,它也应该保持原样.另外,我想截断任何秒数,因为它们对舍入过程没有影响
Basically I need it to RoundUp() or RoundDown() to the nearest 10 minutes explicitly but it should also leave time untouched if it already is in a multiple of 10 minutes. Also I'd like to truncate any seconds to that they have no effect on the rounding procedure
4:50:45-> 4:50:00-> RoundUp()-> 4:50
4:50:45 -> 4:50:00 -> RoundUp() -> 4:50
任何人都没有方便的代码来完成此操作.
Does anyone have any handy code to accomplish this.
我在某处找到了此代码,但是将其四舍五入到5:00-> RoundUp()-> 5:10,而不是保留它不变,因为它已经是10的倍数并且不需要四舍五入.我也不确定几秒钟会如何影响
I found this code somewhere but it rounds 5:00 -> RoundUp() -> 5:10 rather than leaving it intact because its already a multiple of 10 and needs no rounding. Also Im not sure how seconds would effect it
public static DateTime RoundDateTime(this DateTime dt, int minutes, RoundingDirection direction)
{
TimeSpan t;
switch (direction)
{
case RoundingDirection.Up:
t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes, 0)); break;
case RoundingDirection.Down:
t = (dt.Subtract(DateTime.MinValue)); break;
default:
t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes / 2, 0)); break;
}
return DateTime.MinValue.Add(new TimeSpan(0,
(((int)t.TotalMinutes) / minutes) * minutes, 0));
}
希望有人可以编辑该方法以使其对我有用.谢谢
Hope someone can edit that method to make it work for me. Thanks
推荐答案
怎么样:
case RoundingDirection.Up:
t = dt.AddMinutes((60 - dt.Minute) % 10);
case RoundingDirection.Down:
t = dt.AddMinutes(-dt.Minute % 10);
这篇关于DateTime上下舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!