Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c# - 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().

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.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since H specifier can be 2 digit, this method try to parse your 83 with H specifier. Since there is no such an hour, you get FormatException.

For your case, one way to prevent this is putting a leading zero just before your 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...