舍入日期时间对象 [英] Rounding DateTime objects
问题描述
我想将日期/时间四舍五入到图表应用程序的最近间隔.我想要一个如下所示的扩展方法签名,以便可以实现任何精度级别的舍入:
I want to round dates/times to the nearest interval for a charting application. I'd like an extension method signature like follows so that the rounding can be acheived for any level of accuracy:
static DateTime Round(this DateTime date, TimeSpan span);
这个想法是,如果我在十分钟的时间跨度内传递,它将四舍五入到最接近的十分钟间隔.我无法理解这个实现,希望你们中的一个人以前写过或使用过类似的东西.
The idea is that if I pass in a timespan of ten minutes, it will round to the nearest ten minute interval. I can't get my head around the implementation and am hoping one of you will have written or used something similar before.
我认为地板、天花板或最近的实施都可以.
I think either a floor, ceiling or nearest implementation is fine.
有什么想法吗?
感谢@tvanfosson &@ShuggyCoUk,实现如下:
Thanks to @tvanfosson & @ShuggyCoUk, the implementation looks like this:
public static class DateExtensions {
public static DateTime Round(this DateTime date, TimeSpan span) {
long ticks = (date.Ticks + (span.Ticks / 2) + 1)/ span.Ticks;
return new DateTime(ticks * span.Ticks);
}
public static DateTime Floor(this DateTime date, TimeSpan span) {
long ticks = (date.Ticks / span.Ticks);
return new DateTime(ticks * span.Ticks);
}
public static DateTime Ceil(this DateTime date, TimeSpan span) {
long ticks = (date.Ticks + span.Ticks - 1) / span.Ticks;
return new DateTime(ticks * span.Ticks);
}
}
并且是这样调用的:
DateTime nearestHour = DateTime.Now.Round(new TimeSpan(1,0,0));
DateTime minuteCeiling = DateTime.Now.Ceil(new TimeSpan(0,1,0));
DateTime weekFloor = DateTime.Now.Floor(new TimeSpan(7,0,0,0));
...
干杯!
推荐答案
Floor
long ticks = date.Ticks / span.Ticks;
return new DateTime( ticks * span.Ticks, date.Kind );
圆形(中点)
long ticks = (date.Ticks + (span.Ticks / 2) + 1)/ span.Ticks;
return new DateTime( ticks * span.Ticks, date.Kind );
天花板
long ticks = (date.Ticks + span.Ticks - 1)/ span.Ticks;
return new DateTime( ticks * span.Ticks, date.Kind );
这篇关于舍入日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!