How to deal with Rounding-off TimeSpan?

前端 未结 3 1334
刺人心
刺人心 2021-01-02 15:23

I take the difference between two DateTime fields, and store it in a TimeSpan variable, Now I have to round-off the TimeSpan by the following rules:

if the minutes i

3条回答
  •  北海茫月
    2021-01-02 15:47

    TimeSpan is immutable, so you have to create a new one. This is also a perfect case for using extension methods in C#:

    public static class TimeSpanUtility
    {
       public static TimeSpan Round( this TimeSpan ts )
       {
           var sign = ts < TimeSpan.Zero ? -1 : 1;
           var roundBy = Math.Abs(ts.Minutes) >= 30 ? 1 : 0;
           return TimeSpan.FromHours( ts.TotalHours + (sign * roundBy) );
       }
    }
    
    // usage would be:
    var someTimeSpan = new TimeSpan( 2, 45, 15 );
    var roundedTime = someTimeSpan.Round();
    

提交回复
热议问题