我想将DateTime舍入到最近的5秒。这是我目前的做法,但我想知道是否有更好或更简洁的方法?
DateTime now = DateTime.Now; int second = 0; // round to nearest 5 second mark if (now.Second % 5 > 2.5) { // round up second = now.Second + (5 - (now.Second % 5)); } else { // round down second = now.Second - (now.Second % 5); } DateTime rounded = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, second);
DateTime的Ticks计数代表100纳秒的间隔,因此您可以通过舍入到最接近的50000000-tick间隔来舍入到最接近的5秒,如下所示:
DateTime now = DateTime.Now; DateTime rounded = new DateTime(((now.Ticks + 25000000) / 50000000) * 50000000);
这更简洁,但不一定更好。这取决于您是否更喜欢简洁和速度而不是代码清晰。您的更容易理解。