简体   繁体   English

如何将“ yyyyMMdd Hmm”格式的字符串解析为DateTime?

[英]How to parse a string to DateTime with “yyyyMMdd Hmm” format?

I'm having huge problems with solving this problem. 我在解决此问题时遇到了很大的问题。 I'm trying to parse a string using Datetime.ParseExact(). 我正在尝试使用Datetime.ParseExact()解析字符串。

I have the following code: 我有以下代码:

DateTime.ParseExact("20151210 832", "yyyyMMdd Hmm", CultureInfo.InvariantCulture);

I get following error: 我收到以下错误:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: String was not recognized as a valid DateTime. mscorlib.dll中发生了'System.FormatException'类型的未处理异常。其他信息:无法将字符串识别为有效的DateTime。

What am I doing wrong? 我究竟做错了什么? How can I solve this problem? 我怎么解决这个问题?

UPDATE: 更新:

I can also get times like this: 我也可以得到这样的时间:

00:01 => 1
01:00 => 1
01:10 => 10

Since H specifier can be 2 digit, this method try to parse your 83 with H specifier. 由于H指定符可以是2位数,因此该方法尝试使用H指定符解析您的83 Since there is no such an hour, you get FormatException . 由于没有这样一个小时,因此您将获得FormatException

For your case, one way to prevent this is putting a leading zero just before your 8 . 对于您的情况,一种防止这种情况的方法是在8之前放置一个前导零。

var s = "20151210 832";
var result = s.Split(' ')[0] + " 0" + s.Split(' ')[1];
var dt = DateTime.ParseExact(result, "yyyyMMdd Hmm", CultureInfo.InvariantCulture);

Be aware, this will not work for all cases. 请注意,这不适用于所有情况。 For example, if your hour part already two digit, if your single minute does not have leading zero.. etc. 例如,如果您的小时部分已经是两位数,如果您的一分钟没有前导零..等等。

Or you can put delimiter for your all parts but in such a case, you need to manipulate both your string and format. 或者,您可以为所有部分放置定界符,但在这种情况下,您需要同时操纵字符串和格式。

.NET Team suggest this way as well . .NET团队也建议采用这种方式

Just insert a separator before minutes (for example, a whitespace) and then you can parse it like this: 只需在几分钟前插入一个分隔符(例如,空格),然后您可以像下面这样解析它:

string example = "20151210 832";
example = example.Insert(example.Length - 2, " ");
var dateTime = DateTime.ParseExact(example, "yyyyMMdd H mm", CultureInfo.InvariantCulture);

I assume that the datetime string always contains two digits specifying minutes (check an article about Custom Date and Time Format Strings ). 我假设datetime字符串始终包含两个数字,用于指定分钟(请查看有关“ 自定义日期和时间格式字符串”的文章 )。 If my assumption is wrong then this string cannot be parsed. 如果我的假设是错误的,则无法解析此字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM