Gaëtan
Gaëtan

Reputation: 103

Parsing string into Datetime

This may sound really dumb but I'm struggling with some String parsing into some DateTime

This should be pretty easy with DateTime.ParseExact but the thing is I'm not even able to tell what the pattern is.

string[] patterns = new string[] {"dd/MM/yyyy", "ddMMyyyy", "dd/MM/yyyy HH:mm:ss"};
DateTime test = DateTime.ParseExact(DatMEC, patterns, CultureInfo.InvariantCulture,DateTimeStyles.None);

I used to convert my String to DateTime that way, but in a few cases, I'm facing some parsing error.

I logged the String to check the format, and here is what I've got causing the exception :

String dateException="2/1/2004 12:00:00 AM"

I was wondering what was the appropriate pattern for this? I tried the following :

"dd/MM/yyyy HH:mm:ss aaa"
"d/M/yyyy HH:mm:ss a"
"M/d/yyyy HH:mm:ss a"
"MM/dd/yyyy HH:mm:ss aaa"

But none of them seems to work.

Am I missing something? I even wonder if it's parseable?

Upvotes: 1

Views: 63

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98740

You need to use single day and month numbers d and M and use hh specifier instead of HH since it's 12-hour clock time. Also tt specifier for AM designator.

d/M/yyyy hh:mm:ss tt

Further reading:

Upvotes: 6

Related Questions