Parsing TimeSpan with optional minus sign

MSDN says:

The styles parameter affects the interpretation of strings parsed using custom format strings. It determines whether input is interpreted as a negative time interval only if a negative sign is present (TimeSpanStyles.None), or whether it is always interpreted as a negative time interval (TimeSpanStyles.AssumeNegative). If TimeSpanStyles.AssumeNegative is not used, format must include a literal negative sign symbol (such as "-") to successfully parse a negative time interval.

I have try the following:

TimeSpan.ParseExact("-0700", @"\-hhmm", null, TimeSpanStyles.None)

However it returns 07:00:00. And fails for "0700".

If I try:

TimeSpan.ParseExact("-0700", "hhmm", null, TimeSpanStyles.None)

It fails too.

TimeSpan.ParseExact("0700", new string [] { "hhmm", @"\-hhmm" }, null, TimeSpanStyles.None)

Does not fail for both "0700" and "-0700", but always return the positive 07:00:00.

How is it supposed to be used?

Jon Skeet
people
quotationmark

It looks like this isn't supported. From the custom TimeSpan format strings page:

Custom TimeSpan format specifiers also do not include a sign symbol that enables you to differentiate between negative and positive time intervals. To include a sign symbol, you have to construct a format string by using conditional logic. The Other Characters section includes an example.

This does seem really odd though. Ick.

As mentioned in my comment, you could use my Noda Time project's Duration parsing for this; overkill for just this case, but if you had other date/time work in the project, it could be useful.

For example:

var pattern = DurationPattern.CreateWithInvariantCulture("-hhmm");
var timeSpan = pattern.Parse("-0700").Value.ToTimeSpan();

people

See more on this question at Stackoverflow