四舍五入datetime对象对象、四舍五入、datetime

由网友(眼中星河已尽)分享简介:我要舍日期/时间到最近的时间间隔一个图表应用程序。我想扩展方法签名像下面这样的舍入可来达到的任何水平精度:I want to round dates/times to the nearest interval for a charting application. I'd like an extension meth...

我要舍日期/时间到最近的时间间隔一个图表应用程序。我想扩展方法签名像下面这样的舍入可来达到的任何水平精度:

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));
...

干杯!

推荐答案

地板

long ticks = date.Ticks / span.Ticks;

return new DateTime( ticks * span.Ticks );

圆(上中点)

Round (up on midpoint)

long ticks = (date.Ticks + (span.Ticks / 2) + 1)/ span.Ticks;

return new DateTime( ticks * span.Ticks );

天花板

long ticks = (date.Ticks + span.Ticks - 1)/ span.Ticks;

return new DateTime( ticks * span.Ticks );
阅读全文

相关推荐

最新文章