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

后端 未结 7 1074
半阙折子戏
半阙折子戏 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 04:56

    How about this (blending a few answers together)? I think it conveys the meaning well and should handle the edge cases (rounding to the next minute) elegantly due to AddSeconds.

    // truncate to multiple of 5
    int second = 5 * (int) (now.Second / 5);
    DateTime dt = new DateTime(..., second);
    
    // round-up if necessary
    if (now.Second % 5 > 2.5)
    {
        dt = dt.AddSeconds(5);
    }
    

    The Ticks approach as shown by Jay is more concise, but may be a bit less readable. If you use that approach, at least reference TimeSpan.TicksPerSecond.

提交回复
热议问题