为什么 TimeSpan.ParseExact 不起作用 [英] Why does TimeSpan.ParseExact not work

查看:20
本文介绍了为什么 TimeSpan.ParseExact 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

来自 文档:

格式字符串中的任何其他未转义字符,包括空白字符,被解释为自定义格式说明符.在大多数情况下,任何其他未转义字符的存在都会导致格式异常.

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

在它前面加上一个反斜杠("),它被解释为转义字符.这意味着,在 C# 中,格式字符串必须要么被@-引用,要么文字字符前面必须有一个额外的反斜杠.

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 Framework 没有及时定义分隔符的语法间隔.这意味着天和小时之间的分隔符,小时和分钟、分钟和秒、秒和分数second 必须全部被视为格式字符串中的字符文字.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆