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);
Please note that I’ve found these two previous questions, however they truncate rather than round the time.
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:
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.