Question

I have an issue with a string format with a timespan.

string.Format("{0:00}:{1:00}", Math.Floor(ts.TotalHours), ts.Minutes)

Which produce this result 12:08 but the problem is that it can go in minus then it look like this -01:-59 which is not correct it should look like this -01:59. I have tried to use the Math.Abs, but it will just show a 0 even if the number is -56 What is the best way to handle this?

Était-ce utile?

La solution

You can use Math.Abs:

string.Format("{0:00}:{1:00}", Math.Floor((decimal)ts.Hours), Math.Abs(ts.Minutes))

Examples:

TimeSpan ts = new TimeSpan(-1, -1, 0); // returns -01:01

ts = new TimeSpan(-1, 1, 0); // returns -00:59

ts = new TimeSpan(1, 1, 0); // returns 01:01
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top