四舍五入datetime对象 [英] Rounding DateTime objects

查看:448
本文介绍了四舍五入datetime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于四舍五入datetime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆