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?

Was it helpful?

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top