Handle negative time spans

前端 未结 9 542
不知归路
不知归路 2020-12-30 18:50

In my output of a grid, I calculate a TimeSpan and take its TotalHours. e.g.

(Eval(\"WorkedHours\") - Eval(\"BadgedHours\")).TotalH         


        
相关标签:
9条回答
  • 2020-12-30 19:24

    Hi i worked this into a bit of code i have been writing, hope it helps

    (results) is an int variable

    (TimeSpan.FromMinutes(result)) < TimeSpan.Zero ? "-" + TimeSpan.FromMinutes(result).ToString(@"hh\:mm") : "" + TimeSpan.FromMinutes(result).ToString(@"hh\:mm");

    0 讨论(0)
  • 2020-12-30 19:26
    TimeSpan Diff = Date1 - Date2;
    
    if ((int)Diff.TotalDays < 0) { // your code }
    
    0 讨论(0)
  • 2020-12-30 19:30

    Just multiply it by -1 or use an absolute value function.

    0 讨论(0)
  • 2020-12-30 19:37
    static string ToHMString(TimeSpan timespan) { 
        if (timespan.Ticks < 0) return "-" + ToHMString(timespan.Negate());
    
        return timespan.TotalHours.ToString("#0") + ":" + timespan.Minutes.ToString("00");
    }
    
    Console.WriteLine(ToHMString(TimeSpan.FromHours(3)));       //Prints "3:00"
    Console.WriteLine(ToHMString(TimeSpan.FromHours(-27.75)));  //Prints "-28:45"
    

    This will also work correctly if the timespan is longer than 24 hours.

    0 讨论(0)
  • 2020-12-30 19:38

    The simple solution would be to do:

    string format = "HH:mm";
    if(hours < 0)
      format = "-" + format;
    
    hours = Math.Abs(hours)
    
    0 讨论(0)
  • 2020-12-30 19:41

    Isn't there a TimeSpan.Duration method? I think this would handle what you are trying to do.

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