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

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

For example:

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

7条回答
  •  攒了一身酷
    2020-12-02 02:30

    I would say something like that

    var time = DateTime.Now;
    var rounded = time.AddMinutes(
            time.Minute>30 ? -(time.Minute-30) : -time.Minute) 
    

    And you could even do your own extension

    public static class TimeHelper {
       public static DateTime RoundDown (this DateTime time)
       {
           return time.AddMinutes(
             time.Minute>30 ? -(time.Minute-30) : -time.Minute);
       }
    }
    

    EDIT

    This function cut's also the seconds / milliseconds if necessary. Thanks for the hint.

    public static DateTime RoundDown(this DateTime time)
    {
        return time.Subtract(
            new TimeSpan(0, 0, time.Minute > 30 ? (time.Minute - 30) : time.Minute, 
                time.Second, time.Millisecond));
    }
    

提交回复
热议问题