Question

I'm trying to parse a mix of positive and negative times with the c# TimeSpan using this example line:

TimeSpan.TryParseExact("-4:-41:-4.102276", @"[\-]H\:[\-]m\:[\-]s.ffffff", enUS, out time)

Unfortunately this doesn't return anything useful. It just fails and sets time to 0:0:00

Help?

Était-ce utile?

La solution

If "negative" values always have - before each component, you can look for the sign and use two different format strings:

TimeSpan ts;
string s = "-4:-41:-4.102276";
if(s.StartsWith("-"))
    ts = -TimeSpan.ParseExact(s, @"\-h\:\-m\:\-s\.ffffff", enUS);
else
    ts = TimeSpan.ParseExact(s, @"h\:m\:s\.ffffff", enUS);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top