为什么TimeSpan.ParseExact无法正常工作 [英] Why does TimeSpan.ParseExact not work
问题描述
这是一个有点怪异。解析文本字段具有有效时间跨度失败,如果我尝试是precise!
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.
推荐答案
在格式字符串,包括任何其他非转义字符
空格字符,是PTED为自定义格式说明符间$ P $。在
大多数情况下,任何其他非转义字符的presence导致
FormatException。
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).
$ P $用反斜杠(\\),这是PTED作为转义字符间precede它。这意味着,在C#中,格式字符串必须
要么是@ -quoted,或文字字符必须是由pceded $ P $
额外的反斜杠。
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.
.NET框架没有定义的语法在时间分隔符
区间。这意味着,日期和时间之间的分离器,
小时和分钟,分钟和秒,秒的分数
第二必须全部在格式字符串被视为字符文字。
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)
这篇关于为什么TimeSpan.ParseExact无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!