如何使用c#解析缺少分隔符的字符串到DateTime?

时间:2022-11-26 02:07:32

Hey. I have, somehow, this string available "20100205 162206". This is a date and time without any delimiter char.

嘿。不知怎的,我有这个字符串“20100205 162206”。这是一个没有任何分隔符字符的日期和时间。

I need this back as a DateTime in C#. What is the best way?

我需要这个作为C#中的DateTime。什么是最好的方法?

1 个解决方案

#1


31  

Use one of the overloads of DateTime.ParseExact and specify a custom DateTime format string:

使用DateTime.ParseExact的重载之一并指定自定义DateTime格式字符串:

DateTime.ParseExact(
      "20100205 162206",
      "yyyyMMdd HHmmss",
      CultureInfo.InvariantCulture);

What this does is specify an exact format string for your input. (Namely "year-month-day hour-minute-second" without the dashes.)

这样做是为输入指定一个确切的格式字符串。 (即没有破折号的“年 - 月 - 日 - 小时 - 分钟”。)

If your input will always come in in one way, you are safest to use the ParseExact function, because, if you recieve bad data, it allows you to "fail early" rather than operating on inconsistent data.

如果您的输入总是以一种方式进入,那么您最安全地使用ParseExact函数,因为如果您收到错误数据,它会让您“提前失败”而不是操作不一致的数据。

#1


31  

Use one of the overloads of DateTime.ParseExact and specify a custom DateTime format string:

使用DateTime.ParseExact的重载之一并指定自定义DateTime格式字符串:

DateTime.ParseExact(
      "20100205 162206",
      "yyyyMMdd HHmmss",
      CultureInfo.InvariantCulture);

What this does is specify an exact format string for your input. (Namely "year-month-day hour-minute-second" without the dashes.)

这样做是为输入指定一个确切的格式字符串。 (即没有破折号的“年 - 月 - 日 - 小时 - 分钟”。)

If your input will always come in in one way, you are safest to use the ParseExact function, because, if you recieve bad data, it allows you to "fail early" rather than operating on inconsistent data.

如果您的输入总是以一种方式进入,那么您最安全地使用ParseExact函数,因为如果您收到错误数据,它会让您“提前失败”而不是操作不一致的数据。