Handle negative time spans

烂漫一生 提交于 2019-11-30 08:07:31
Jared

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

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.

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

Eugeniu Torica

There is a Negate method in the TimeSpan class.

Link to the MSDN documentation: TimeSpan.Negate Method()

its working .try this

mytimespam.Negate();

jvenema

The simple solution would be to do:

string format = "HH:mm";
if(hours < 0)
  format = "-" + format;

hours = Math.Abs(hours)

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");

sajin k

I checked to every where.But i didnt get a correct answer that why i used this way to finish

TimeSpan diff = actualout.Subtract(actualin);
 string a =(diff.ToString()).ToString();
if(a.Contains("-"))
 {        
 diff = new TimeSpan(0,0,0,0);
}
Mohammed Hedach
TimeSpan Diff = Date1 - Date2;

if ((int)Diff.TotalDays < 0) { // your code }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!