有没有在C#更好的方式来圆一个日期时间到最近的5秒了吗? [英] Is there a better way in C# to round a DateTime to the nearest 5 seconds?

查看:168
本文介绍了有没有在C#更好的方式来圆一个日期时间到最近的5秒了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要圆一个DateTime至最接近的5秒。这是这样的,我现在这样做,但我不知道是否有一个更好或更简洁的方式?

I want to round a DateTime to the nearest 5 seconds. This is the way I'm currently doing it but I was wondering if there was a better or more concise way?

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

请注意,我发现<一href="http://stackoverflow.com/questions/152774/is-there-a-better-way-to-trim-a-datetime-to-a-specific-$p$pcision">these <一href="http://stackoverflow.com/questions/166145/whats-the-best-way-to-round-a-net-date-object-to-the-nearest-minute-closed">two previous问题,但他们的,而不是的时间。

Please note that I've found these two previous questions, however they truncate rather than round the time.

推荐答案

蜱的日期时间再presents 100纳秒的时间间隔数,让你圆到最近的5秒就可以四舍五入到最接近的5000-TICK这样的时间间隔:

The Ticks count of a DateTime represents 100-nanosecond intervals, so you can round to the nearest 5 seconds by rounding to the nearest 50000000-tick interval like this:

  DateTime now = DateTime.Now;
  DateTime rounded = new DateTime(((now.Ticks + 25000000) / 50000000) * 50000000);

这是更简洁,但不一定好。这要看你是否preFER简洁和速度超过code清晰度。你可以说是比较容易理解。

That's more concise, but not necessarily better. It depends on whether you prefer brevity and speed over code clarity. Yours is arguably easier to understand.

这篇关于有没有在C#更好的方式来圆一个日期时间到最近的5秒了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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