我希望能够解析时间 (小时,分钟,秒)的时间串,其中小时数从0到23,以及前一个零小时数是可选的。
我希望能够解析为有效的DateTime对象的时间字符串示例:
212540 061525 94505我正在尝试使用C#方法DateTime.ParseExact来管理解析,但是我不能为它的生活提供一个格式字符串,它可以处理“没有先前零的单位数小时”场景。
我应该如何指定DateTime.ParseExact格式字符串,以便用相同的代码行充分解析上述所有示例?
受自定义日期和时间格式的MSDN页面的启发,我尝试了以下方法:
DateTime.ParseExact(time_string, "Hmmss", CultureInfo.InvariantCulture); DateTime.ParseExact(time_string, "%Hmmss", CultureInfo.InvariantCulture); DateTime.ParseExact(time_string, "HHmmss", CultureInfo.InvariantCulture);所有这些格式字符串都适用于上面的两个示例,但面临的是一位数小时且没有零之前,所有公式都会引发FormatException 。
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.
Examples of time strings that I want to be able to parse into valid DateTime objects:
212540 061525 94505I 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.
How should I specify the DateTime.ParseExact format string to sufficiently parse all examples above with the same line of code?
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);All these format strings work for the first two example cases above, but faced with a single-digit hour and no preceding zero, all formulations throw a FormatException.
最满意答案
如果你知道你总是有六个字符,你可以填充你的输入字符串。
string input = "94505"; if(input.Length < 6) input = input.PadLeft(6, '0');(或者如果您有其他有效的格式更短,请使用input.Length == 5 )。
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');(Or use input.Length == 5 if you have other valid formats that are shorter).
更多推荐
发布评论