如何处理 TimeSpan.TryParseExact(...) 中的格式说明符
How to handle format specifiers in TimeSpan.TryParseExact(...)
我想将包含格式说明符的时间跨度字符串解析为 TimeSpan. For example: "2h 57m 43s"
. h, m, and s are all format specifiers. See Custom TimeSpan format strings - .NET | Microsoft Docs 以获取更多信息。
根据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.
我试过:"hh'h 'mm'm 'ss's'"
和 @"hh\h mm\m ss\s"
都没有成功。
TimeSpan tracker;
if (TimeSpan.TryParseExact("2h 57m 43s", @"hh\h mm\m ss\s", null, out tracker))
{
Console.WriteLine(tracker);
}
else
{
Console.WriteLine("fail");
}
这总是失败。我期望 02:57:43
的 TimeSpan。我目前正在使用正则表达式解决此问题,但想知道如何使用 TryParseExact 解析此字符串?
您可以在格式说明符后使用 %
,并且您需要转义 space 文字。
TimeSpan.TryParseExact("2h 57m 43s", @"h%\h\ m%\m\ s%\s", null, out tracker)
代码中的小更新:
TimeSpan tracker;
if (TimeSpan.TryParseExact("02h 57m 43s", @"hh\h' 'mm\m' 'ss\s", null, out tracker))
{
Console.WriteLine(tracker);
}
else
{
Console.WriteLine("fail");
}
问题是无法理解 space 并且两次 'h' 与值不匹配。
希望对您有所帮助!
我想将包含格式说明符的时间跨度字符串解析为 TimeSpan. For example: "2h 57m 43s"
. h, m, and s are all format specifiers. See Custom TimeSpan format strings - .NET | Microsoft Docs 以获取更多信息。
根据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.
我试过:"hh'h 'mm'm 'ss's'"
和 @"hh\h mm\m ss\s"
都没有成功。
TimeSpan tracker;
if (TimeSpan.TryParseExact("2h 57m 43s", @"hh\h mm\m ss\s", null, out tracker))
{
Console.WriteLine(tracker);
}
else
{
Console.WriteLine("fail");
}
这总是失败。我期望 02:57:43
的 TimeSpan。我目前正在使用正则表达式解决此问题,但想知道如何使用 TryParseExact 解析此字符串?
您可以在格式说明符后使用 %
,并且您需要转义 space 文字。
TimeSpan.TryParseExact("2h 57m 43s", @"h%\h\ m%\m\ s%\s", null, out tracker)
代码中的小更新:
TimeSpan tracker;
if (TimeSpan.TryParseExact("02h 57m 43s", @"hh\h' 'mm\m' 'ss\s", null, out tracker))
{
Console.WriteLine(tracker);
}
else
{
Console.WriteLine("fail");
}
问题是无法理解 space 并且两次 'h' 与值不匹配。
希望对您有所帮助!