Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - How to convert a string containing AM/PM to DateTime?

How can i parse a string like this: "2/22/2015 9:54:02 AM" to a DateTime instance?

i am currently using the DateTime.ParseExact method but without the AM/PM i.e:

 DateTime.ParseExact("2/22/2015 9:54:02", "M/dd/yyyy HH:mm:ss")

I would like to be able to parse the AM/PM signs as well.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should change the hour format (H) to lowercase like this:

DateTime.ParseExact("2/22/2015 9:54:02 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

Uppercase "H" indicates a 24-hour time and lowercase "h" indicates 12-hour time and will respect the AM/PM in the candidate string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...