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

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

For example:

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

7条回答
  •  臣服心动
    2020-12-02 02:15

    Here's how I handled it. Below is the base method and an overload to round to the nearest 30 minutes:

    public static DateTime RoundMinutes(this DateTime value)
    {
        return RoundMinutes(value, 30);
    }
    
    public static DateTime RoundMinutes(this DateTime value, int roundMinutes)
    {
        DateTime result = new DateTime(value.Ticks);
    
        int minutes = value.Minute;
        int hour = value.Hour;
        int minuteMod = minutes % roundMinutes;
    
        if (minuteMod <= (roundMinutes / 2))
        {
            result = result.AddMinutes(-minuteMod);
        }
        else
        {
            result = result.AddMinutes(roundMinutes - minuteMod);
        }
    
        return result;
    }
    

提交回复
热议问题