Time analysis using the optional minus sign

MSDN says :

The styles parameter affects the interpretation of strings parsed using custom-format strings. It determines whether an input is interpreted as a negative time interval only if a negative sign is present (TimeSpanStyles.None), or it is always interpreted as a negative time interval (TimeSpanStyles.AssumeNegative). If TimeSpanStyles.AssumeNegative is not used, the format must contain a negative letter character (for example, “-”) for successful analysis of the negative time interval.

I will try the following:

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

However, he returns 07:00:00. And does not work for "0700."

If I try:

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

Crash too.

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

It does not work for both "0700" and "-0700", but always returns positive 07:00:00.

How should it be used?

+6
source share
2 answers

It seems like this is not supported. From custom TimeSpan format strings :

Custom TimeSpan format specifiers also do not include a character character, which allows you to distinguish between negative and positive time intervals. To include a character sign, you must construct a format string using conditional logic. See the Other Symbols section for an example.

It really seems weird. Hk.

As mentioned in my comment, you can use my Noda Time Duration parsing project ; overkill for this case, but if you had a different date / time of work in the project, this may be useful.

For instance:

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

It seems you annoyingly need to check yourself if it starts with a host -

 // tsPos = 07:00:00 string pos = "0700"; TimeSpan tsPos = TimeSpan.ParseExact(pos, new string [] { "hhmm", @"\-hhmm" }, null, pos[0] == '-' ? TimeSpanStyles.AssumeNegative : TimeSpanStyles.None); // tsNeg = -07:00:00 string neg = "-0700"; TimeSpan tsNeg = TimeSpan.ParseExact(neg, new string [] { "hhmm", @"\-hhmm" }, null, neg[0] == '-' ? TimeSpanStyles.AssumeNegative : TimeSpanStyles.None); 
+1
source

Source: https://habr.com/ru/post/981058/


All Articles