Getting an exception when using the DateTime.Parse method

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

If I delete the "+0200" part, it works fine, but of course it does not show the correct local time. What is wrong with that?

+4
source share
3 answers

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

  • GMT used separately, for example. Mon, Jan 03 2011 17:29:44 GMT , or

  • The time zone offset indicated without GMT , for example. Mon, Jan 03 2011 19:29:44+02:00 .

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

+7
source

It just means that the timezone offset is not the expected part of the default format strings.

If you know what format you expect, I suggest you call DateTime.ParseExact (or DateTime.TryParseExact ), indicating the format (s) to try. See the documentation for custom date / time format strings for more information.

+4
source

You have two errors.

First, do not use the Parse method. More correct is TryParse. Secondly, you will have globalization issues when you use Parse or TryParse with no arguments.

For example, see this code:

DateTime.Parse ("02/01/2011"); In the USA, this is January 2. In Germany, this is February 1st.

So, I recommend you use the formats from this article .

+2
source

Source: https://habr.com/ru/post/1334183/


All Articles