views:

538

answers:

2

Hi,

I've done some simple string -> DateTime conversions before using DateTime.ParseExact(), but I have a string that I can't seem to get parsed properly. I'm probably doing something very obvious wrong but I just can't see what it is.

The code is as follows:

string date = "Tue Jun 23, 2009 2:23 pm";
DateTime lastupdate = DateTime.ParseExact(date, "ddd MMM dd, yyyy h:mm tt", null);

Running it gives a FormatException. Is my formatting string incorrect?

ps I've tried to use p.m. rather than pm in the input string but that didn't help either.

A: 

Do you need to parse it exactly, or can you not just use DateTime.Parse?

ck
+4  A: 

Try this:

DateTime lastupdate = DateTime.ParseExact(date, "ddd MMM dd, yyyy h:mm tt", new System.Globalization.CultureInfo("en-us"));

An error would occur if the culture was for example "fr-fr" or "de-de".

Why is this marked as correct? Your date is incorrect, which is causing the error.
GenericTypeTea
Maybe he edited it, but it's June not January.
That did it. I think my system's regional settings are set to Netherlands, so it's probably using that culture as well then. I had (still have) no idea what the supplied culture would do in the parsing process, as I literally supply the formatting of the string. My mistake. I'll do a bit of further reading into these functions :-)
Jerry
Didn't edit the date. There's nothing wrong with it. June 23rd was a tuesday. I did edit the post to add the exception in there though. But weiqure's solution is valid, is it not?
Jerry
Yes, the date wasn't edited, it was me!
GenericTypeTea