解析C#字符串日期时间字符串、日期、时间

2023-09-02 10:20:24 作者:日光倾城也未必温暖

我有一个这样的字符串: 250920111414

I have a string like this: 250920111414

我要创建从该字符串DateTime对象。截至目前,我用串并做到这一点是这样的:

I want to create a DateTime object from that string. As of now, I use substring and do it like this:

string date = 250920111414;

int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);

是否有可能使用字符串格式,做同样的,无子?

Is it possible to use string format, to do the same, without substring?

推荐答案

当然可以。从您的字符串猜测格式,你可以使用ParseExact

Absolutely. Guessing the format from your string, you can use ParseExact

string format = "ddMMyyyyHHmm";

DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);

或TryParseExact:

DateTime dt;
bool success = DateTime.TryParseExact(value, format, 
                     CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

后者调用只会返回的解析故障,而不是抛出一个异常 - 如果可能有坏的数据,应该不会导致整个任务失败(例如,它的用户输入,而你只是想提示他们),那么这是一个更好的通话使用。

The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.

编辑:有关格式字符串的详细信息的详细信息,请参见自定义日期和时间格式字符串 MSDN研究。

For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.