4

So, i have this string "Date: Mon Jan 03 2011 19:29:44 GMT+0200", and when i use DateTime.Parse(date).ToString(); i'm getting "String was not recognized as a valid DateTime."

If i remove the '+0200' part it works ok, but ofcourse it doesn't show the correct local time. What's wrong with that?

3 Answers 3

7

From the documentation, it seems that DateTime.Parse() only understands:

  • The GMT designator, used alone, e.g. Mon, Jan 03 2011 17:29:44 GMT, or

  • A time zone offset specified without the GMT designator, e.g. Mon, Jan 03 2011 19:29:44+02:00.

You might want to convert your date string to the second form.

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

Comments

4

It just means that the time zone offset isn't an expected part of the default format strings.

If you know what format you're expecting, I suggest you call DateTime.ParseExact (or DateTime.TryParseExact), specifying the format(s) to try. Look at the documentation for custom date/time format strings for more details.

1 Comment

@user361633: Don't forget you can provide multiple patterns - I'd expect you to know at least a range of expected formats.
2

You have two mistakes.

First - don`t use Parse method. More correct is TryParse. Second - you will have globalisation issues, when you use Parse or TryParse without arguments.

For example, see this code:

DateTime.Parse( "01.02.2011" ); In the USA it is 2nd of January. In the Germany it is 1st of February.

So, I recomment you to use formats from this article.

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.