这个时间跨度有什么问题?ParseExact线

本文关键字:ParseExact 问题 什么 时间跨度 | 更新日期: 2023-09-27 17:49:30

我收到一个FormatError异常从这个调用TimeSpan。但是我正在阅读的MSDN文档说这种格式应该是正确的:

TimeSpan timeSpan = TimeSpan.ParseExact("172100", "HHmmss", CultureInfo.InvariantCulture);

谁能告诉我为什么这不起作用?我对DateTime的调用做了几乎完全相同的事情。ParseExact和这个工作很好:

DateTime datetTime = DateTime.ParseExact("090820", "yyMMdd", CultureInfo.InvariantCulture);

这个时间跨度有什么问题?ParseExact线

TimeSpan不使用与DateTime相同的格式规则。

你想要hhmmss,而不是hhmmss。

您正在MSDN中查找错误的页面-您想要这样的内容:

http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

参考这个更准确的文档:http://msdn.microsoft.com/en-us/library/ee372287.aspx

您需要使用hh几个小时,而不是HH

根据自定义时间跨度格式字符串,小时由"h"而不是"h"表示。

所以这个很好:

TimeSpan timeSpan = TimeSpan.ParseExact("172100", "hhmmss", 
                                        CultureInfo.InvariantCulture);

您链接到的文档用于自定义日期和时间格式字符串,它们是不相同的。它们用于DateTime.ParseExact等;我链接到的文档是TimeSpan.ParseExact

将字符串解析为DateTime值,然后减去它的Date值,以TimeSpan的形式获得时间:

DateTime t = DateTime.ParseExact("172100", "HHmmss", CultureInfo.InvariantCulture);
TimeSpan time = t - t.Date;

您尝试使用DateTime格式字符串来解析TimeSpanTimeSpan有自己的(略有不同的)格式字符串。查看MSDN的完整列表:自定义时间跨度格式字符串

特别地,将HH更改为hh。这将给你:

TimeSpan timeSpan = TimeSpan.ParseExact("172100",
                                        "hhmmss", // Note this parameter
                                        CultureInfo.InvariantCulture);