Is there a better way in C# to round a DateTime to the nearest 5 seconds?

后端 未结 7 1019
半阙折子戏
半阙折子戏 2020-12-09 04:33

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?

         


        
相关标签:
7条回答
  • 2020-12-09 05:12

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

    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.

    0 讨论(0)
提交回复
热议问题