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
116 views
in Technique[技术] by (71.8m points)

c# - How to convert datetime string in format MMMdyyyyhhmmtt to datetime object?

I have tried like below:

DateTime.ParseExact("Feb520161000PM", 
"MMMdyyyyhhmmtt", CultureInfo.InvariantCulture)

But it's giving FormatException.

Interestingly

DateTime.ParseExact(DateTime.Now.ToString("MMMdyyyyhhmmtt"), "MMMdyyyyhhmmtt", 
CultureInfo.InvariantCulture)

This is also giving format exception.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The format is not parseable with regular parsing which work from left to right - you need custom code that parses value from right to left instead as you want leftmost number to be variable width ("Feb111111111PM").

If possible - change format to one with fixed width fields (preferably ISO8601). Otherwise split string manually and construct date from resulting parts (time part would work fine by itself, so just need to manually parse date part).

Some other approaches and info can be found in similar post about time - DateTime.ParseExact - how to parse single- and double-digit hours with same format string?


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

...