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

后端 未结 7 1058
半阙折子戏
半阙折子戏 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:01

    I couldn't recognize the difference between C# and a bar of soap (well, I couldn't when I originally wrote this answer, things have changed quite a bit in the years since) but, if you're looking for a more concise solution, I would just put the whole thing in a function - there's little that will be more concise in your code than a simple call to said function:

    DateTime rounded = roundTo5Secs (DateTime.Now);
    

    Then you can put whatever you want in the function and just document how it works, such as (assuming these are all integer operations):

    secBase = now.Second / 5;
    secExtra = now.Second % 5;
    if (secExtra > 2) {
        return new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute,
            secBase + 5);
    }
    return new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute,
        secBase);
    

    You may also need some extra checks if secBase goes to 60 (unless C# DateTime objects are smart enough to bump up the minute (and hour if minute goes to 60, and so on).

提交回复
热议问题