How to deal with Rounding-off TimeSpan?

前端 未结 3 1333
刺人心
刺人心 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:41

    How about:

    public static TimeSpan Round(TimeSpan input)
    {
        if (input < TimeSpan.Zero)
        {
            return -Round(-input);
        }
        int hours = (int) input.TotalHours;
        if (input.Minutes >= 30)
        {
            hours++;
        }
        return TimeSpan.FromHours(hours);
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2021-01-02 15:50

    You can use

    double v = span.TotalHours;     
    v = Math.Round(v, MidpointRounding.AwayFromZero);
    span = TimeSpan.FromHours(v);
    

    It depends on whether I understood your rules for negative values correctly.

    0 讨论(0)
提交回复
热议问题