【问题标题】:Exception thrown when parsing seemingly correct time span解析看似正确的时间跨度时抛出异常
【发布时间】:2012-10-04 16:22:24
【问题描述】:

我正在使用TimeSpan.ParseExact 方法来解析时间跨度。但是,为什么下面会失败并抛出异常呢?

string time = "23:10:00";
string format = "HH:mm:ss";
TimeSpan timeSpan = TimeSpan.ParseExact(time, format, CultureInfo.InvariantCulture);

从MSDN上Custom Date and Time Format Strings的文章来看,这个输入字符串的格式是正确的。有什么想法吗?

【问题讨论】:

  • 这看起来不像 C++。应该标记为 C# 还是 CLI?

标签: c# parsing timespan


【解决方案1】:

您链接到自定义 DateTime 格式说明符 - 但您没有解析为 DateTime,而是解析为 TimeSpan,因此您需要 custom TimeSpan format specifiers - 这意味着使用“hh”而不是“嗯”。此外,根据文档,您需要转义冒号 - 所以您真的想要:

string format = @"hh\:mm\:ss";

我已验证这适用于您的示例值。

【讨论】:

  • 伙计,为什么格式字符串必须不同?这将在我们的代码中造成严重的问题。再次感谢好友。
  • @Steztric:如果您将TimeSpan 格式和DateTime 格式视为可互换的,它只会在您的代码中引起问题。它们是非常不同的类型,因此您应该区别对待格式:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
相关资源
最近更新 更多