我希望能够解析时间(小时、分钟、秒)的字符串,其中小时从 0 到 23,并且前面的一位数小时的零是可选的。
我希望能够解析为有效 DateTime
对象的 time 字符串示例:
- 212540
- 061525
- 94505
我正在尝试使用 C# 方法 DateTime.ParseExact来管理解析,但我终其一生都无法想出一个格式字符串来处理“前面没有零的个位数小时”场景。
我应该如何指定 DateTime.ParseExact
格式字符串以使用同一行代码充分解析上述所有示例?
灵感来自 MSDN page on custom date and time formats ,我尝试了以下方法:
DateTime.ParseExact(time_string, "Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "%Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "HHmmss", CultureInfo.InvariantCulture);
所有这些格式字符串都适用于上面的前两个示例情况,但面对个位数的小时且前面没有零,所有公式都会抛出 FormatException
。
最佳答案
您可以像这样在小时、分钟和秒之间插入分隔符:
string timeString = "94505";
string formatedTimeString = Regex.Replace(str, @"\d{1,2}(?=(\d{2})+$)", "$&:");
var datetime = DateTime.ParseExact(formatedTimeString, "H:mm:ss", CultureInfo.InvariantCulture);
更新:
我找到了 the cause of failure当使用格式字符串 "Hmmss"
解析 "94505"
时:
What's happening is that H, m and s actually grabs two digits when they can, even if there won't be enough digits for the rest of the format. So the for example with the format Hmm and the digits 123, H would grab 12 and there would only be a 3 left. And mm requires two digits, so it fails.
所以基本上您有两种选择来处理“前面没有零的个位数小时”场景:
更改时间格式:将小时放在末尾(例如,
"ssmmH"
或"mmssH"
)或使用分隔符(例如,“高:毫米:ss”
)像我之前建议的那样修改字符串或像 keyboardP has .
关于c# - DateTime.ParseExact - 如何解析具有相同格式字符串的一位数和两位数的小时数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18979049/