1

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.

1
  • Jerry, I can't see either since you didn't post the exception. Commented Jul 7, 2009 at 9:47

2 Answers 2

4

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Why is this marked as correct? Your date is incorrect, which is causing the error.
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 :-)
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?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.