DateTime.ParseExact

编程入门 行业动态 更新时间:2024-10-27 19:20:07
DateTime.ParseExact - 如何解析具有相同格式字符串的单位和双位小时?(DateTime.ParseExact - how to parse single- and double-digit hours with same format string?)

我希望能够解析时间 (小时,分钟,秒)的时间串,其中小时数从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 94505

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.

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).

更多推荐

本文发布于:2023-08-06 12:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448892.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DateTime   ParseExact

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!