Jack Marchetti
Jack Marchetti

Reputation: 15754

DateTime keeps throwing an exception for "string not recognized as valid DateTime"

Here's the string:

string date = "Fri Feb 17 15:50:42 +00:00 2012";

I'm just trying to parse it using:

DateTime.Parse(date, new Culture("en-us"));
DateTime.Parse(date);

No matter what I do it keeps coming back as invalid string.

What am I doing wrong?

Upvotes: 0

Views: 221

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108880

I'd look into specifying the format you want using ParseExact:

If you want a DateTime use DateTime.ParseExact:

DateTime.ParseExact("Fri Feb 17 15:50:42 +00:00 2012",
                    "ddd MMM dd HH:mm:ss zzz yyyy",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.AdjustToUniversal)

Or since you're handling arbitrary offsets, DateTimeOffset is probably the better choice:

DateTimeOffset.ParseExact("Fri Feb 17 15:50:42 +00:00 2012",
                          "ddd MMM dd HH:mm:ss zzz yyyy",
                          CultureInfo.InvariantCulture)

Upvotes: 5

Related Questions