DateTime.ParseExact - 如何解析格式同串单精度和双位数字的小时? [英] DateTime.ParseExact - how to parse single- and double-digit hours with same format string?
问题描述
我希望能够解析中的时间的(小时,分,秒),其中从0到23小时,并在前面的一个位小时零是可选的。字符串
I want to be able to parse strings of time (hours, minutes, seconds) where the hours run from 0 to 23, and where the preceding zero for one-digit hours is optional.
的例子的时间的,我希望能够解析为有效的的DateTime
对象的字符串
Examples of time strings that I want to be able to parse into valid DateTime
objects:
- 212540
- 061525
- 94505
我想用C#方法的 DateTime.ParseExact 以管理解析,但我不能为它的生活拿出一个格式字符串,可以处理的个位数小时无零方案前面。
I am trying to use the C# method DateTime.ParseExact to manage the parsing, but I cannot for the life of it come up with a format string that can handle the "single-digit hour without preceding zero" scenario.
我应该如何指定 DateTime.ParseExact
格式字符串充分解析上面相同的代码行的所有实例?
How should I specify the DateTime.ParseExact
format string to sufficiently parse all examples above with the same line of code?
由 MSDN页面上自定义日期启发和时间格式,我曾尝试以下方法:
Inspired by the MSDN page on custom date and time formats, I have tried the following approaches:
DateTime.ParseExact(time_string, "Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "%Hmmss", CultureInfo.InvariantCulture);
DateTime.ParseExact(time_string, "HHmmss", CultureInfo.InvariantCulture);
所有这些格式字符串的头两个示例上述情况下工作,但面临着一个单数字小时没有前面的零,所有制剂抛出 FormatException
。
推荐答案
您。可以垫您输入的字符串,如果你知道你将永远有六个字符
You could pad your input string if you know that you'll always have six characters.
string input = "94505";
if(input.Length < 6)
input = input.PadLeft(6, '0');
(或者使用 input.Length == 5
如果您有其他有效的格式是短)。
(Or use input.Length == 5
if you have other valid formats that are shorter).
这篇关于DateTime.ParseExact - 如何解析格式同串单精度和双位数字的小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!