Is there a simple function for rounding a DateTime down to the nearest 30 minutes, in C#?

后端 未结 7 1073
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 01:35

For example:

2011-08-11 16:59 becomes 2011-08-11 16:30

7条回答
  •  忘掉有多难
    2020-12-02 02:17

    Exploiting some math

    var input = DateTime.Now; // or however you get DateTime
    var rounded = input.AddMinutes(-input.TimeOfDay.TotalMinutes % 30d);
    

    Note that TimeOfDay is a TimeSpan and its TotalMinutes property is a double and that the modulus operator functions on doubles like follows:

    47.51 % 30d == 17.51

    16.2 % 30d == 16.2

    768.7 % 30d == 18.7

    You could change the 30d to any value you like other than zero. Changing to 15 rounds down to 15 minute intervals for instance. Changing from 30d to -30d, didn't change the results from the tests that I ran.

    You could create a rounding extension method (providing this rounding method for all DateTime values):

    public static class DateTimeExtensions
    {
        public static DateTime Round(this DateTime self, double minutesInInterval)
        {
            if (minutesInInterval == 0d) throw new ArgumentOutOfRangeException("minutesInInterval");
            return self.AddMinutes(-self.TimeOfDay.TotalMinutes % minutesInInterval);
        }
    }
    

提交回复
热议问题