DateTime Round Up and Down

前端 未结 5 1853
面向向阳花
面向向阳花 2021-02-07 12:58

Ive been looking for a proper rounding mechanism but nothing I find seems to be exactly what I need.

I need to round up and round down seperately and I also need to acco

5条回答
  •  既然无缘
    2021-02-07 13:34

    This will let you round according to any interval given.

    public static class DateTimeExtensions
    {
      public static DateTime Floor(this DateTime dateTime, TimeSpan interval)
      {
        return dateTime.AddTicks(-(dateTime.Ticks % interval.Ticks));
      }
    
      public static DateTime Ceiling(this DateTime dateTime, TimeSpan interval)
      {
        var overflow = dateTime.Ticks % interval.Ticks;
    
        return overflow == 0 ? dateTime : dateTime.AddTicks(interval.Ticks - overflow);
      }
    
      public static DateTime Round(this DateTime dateTime, TimeSpan interval)
      {
        var halfIntervalTicks = (interval.Ticks + 1) >> 1;
    
        return dateTime.AddTicks(halfIntervalTicks - ((dateTime.Ticks + halfIntervalTicks) % interval.Ticks));
      }
    }
    

    To take care of truncating the seconds, I would simply subtract the seconds and milliseconds from the date-time before sending them into the rounding functions.

提交回复
热议问题