3

Possible Duplicate:
Parse Datetime string

I'm trying to parse the following DateTime in C#:

string date = "Wed Jul 25 19:41:36 2012 +0200"
DateTime result = DateTime.Parse(date);

And I'm getting the following error:

System.FormatException : String was not recognized as a valid DateTime.

Anybody knows what is the problem here?

2
  • @PeterRitchie Definite duplicate if you ignore the format, I've personally answered 3 of these now, but technically the format has changed each time :-) Commented Jul 26, 2012 at 15:44
  • Not sure why people are closing as duplicate... telling the OP that parse strings exist doesn't answer the entire question. Commented Jul 26, 2012 at 15:55

2 Answers 2

11

You can use DateTime.ParseExact() for that. For example

UPDATED:

string dateString = "Your date";
string format = "ddd MMM dd HH:mm:ss yyyy %K";
DateTime dateTime = DateTime.ParseExact(dateString, format, 
              CultureInfo.InvariantCulture);
Console.WriteLine(dateTime);

Documentation Here and DateTime string formatting options here.

You can also view here {Complr.com}

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

5 Comments

Not to be picky, as that is very close, but it doesn't cater for the time-zone offset that the OP has included.
I just updated the answer after some research. sorry for the first one.
Ok, thanks, I will accept your answer, you was the first ...
@AdamHouldsworth thank you for the link on formats.. i upvoted your answer too.
@John No problem, ditto after the edit :-)
6

You need to specify the parsing format as that is non-standard. DateTime.ParseExact allows you to specify the format.

Something like this will work, however I've yet to verify if that time-zone part is working correctly, seems to give me a date/time at 1800 hrs... Ah this is because where I am it is BST (GMT +1).

    static void Main(string[] args)
    {
        string date = "Wed Jul 25 19:41:36 2012 +0200";
        string format = "ddd MMM dd HH:mm:ss yyyy %K";
        //string format = "ddd MMM dd HH:mm:ss yyyy zzz"; // Also works.
        DateTime dateTime = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
        Console.ReadLine();
    }

DateTime string formatting options are documented here, you can create a parse string using any combination of these to parse a DateTime successfully.

Another example of this can be found here: Parse DateTime From Odd Format

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.