This is a bit wierd. Parsing a text field with a valid timespan fails if I try to be precise!
const string tmp = "17:23:24"; //works var t1 = TimeSpan.Parse(tmp); //fails var t2 = TimeSpan.ParseExact(tmp, "hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
The second parse fails with an exception "Input string was not in a correct format." from DateTime.
From the documentation:
Any other unescaped character in a format string, including a white-space character, is interpreted as a custom format specifier. In most cases, the presence of any other unescaped character results in a FormatException.
There are two ways to include a literal character in a format string:
Enclose it in single quotation marks (the literal string delimiter).
Precede it with a backslash ("\"), which is interpreted as an escape character. This means that, in C#, the format string must either be @-quoted, or the literal character must be preceded by an additional backslash.
The .NET Framework does not define a grammar for separators in time intervals. This means that the separators between days and hours, hours and minutes, minutes and seconds, and seconds and fractions of a second must all be treated as character literals in a format string.
So, the solution is to specify the format string as
TimeSpan.ParseExact(tmp, "hh\\:mm\\:ss", CultureInfo.InvariantCulture)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With