views:

400

answers:

4

in my output of a grid

i calculate a TimeSpan and take its TotalHours ex. (Eval("WorkedHours") - Eval("BadgedHours")).TotalHours

goal is to show this TotalHours as : 39:44 so. First value 7.5 to 07:30

no problem.. but if its negative!

I can create a TimeSpan object from Hours with TimeSpan.FromHours( (Eval("WorkedHours") - Eval("BadgedHours")).TotalHours)

now if its negative i cant convert it to a datetime and use the .ToString("HH:mm") method.

And the timespan object does not support the format string .

Thx

+3  A: 

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

Daniel A. White
A: 

The simple solution would be to do:

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

hours = Math.Abs(hours)

jvenema
A: 
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.

SLaks
A: 

Thank you guys!