gpt4 book ai didi

c# - 为什么 TimeSpan.ParseExact 不起作用

转载 作者:IT王子 更新时间:2023-10-29 04:03:04 24 4
gpt4 key购买 nike

这有点奇怪。如果我尝试精确,则解析具有有效时间跨度的文本字段会失败!

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);

第二次解析失败,出现异常“输入字符串的格式不正确”。来自日期时间。

最佳答案

来自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.

因此,解决方案是将格式字符串指定为

TimeSpan.ParseExact(tmp, "hh\\:mm\\:ss", CultureInfo.InvariantCulture)

关于c# - 为什么 TimeSpan.ParseExact 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11719055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com