I'd like to parse a time span string that contains format specifiers into a TimeSpan. For example: "2h 57m 43s"
. h, m, and s are all format specifiers. See Custom TimeSpan format strings - .NET | Microsoft Docs for more info.
According to the docs:
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.
I've tried: "hh'h 'mm'm 'ss's'"
and @"hh\h mm\m ss\s"
with no luck.
TimeSpan tracker;
if (TimeSpan.TryParseExact("2h 57m 43s", @"hh\h mm\m ss\s", null, out tracker))
{
Console.WriteLine(tracker);
}
else
{
Console.WriteLine("fail");
}
This always fails. I'm expecting a TimeSpan of 02:57:43
. I'm currently working around this issue using a Regex, but would like to know how can I parse this string using TryParseExact?
You can use %
after the format specifier and you need to escape the space literals.
TimeSpan.TryParseExact("2h 57m 43s", @"h%\h\ m%\m\ s%\s", null, out tracker)