DateTime.Parse with a +

I have a piece of code that parses and validates user input:

DateTime myDateTime = DateTime.Parse(userInput,currentCulture); 

The current culture is set (before en-ca or fr-ca) and the user input is always in ISO 8601 format "yyyy-MM-dd".

If the user enters 1900-01-01, the date is created as expected. If the input is "1900-01 + 01", the date creation time is 1899-12-31 6:00:00 PM No exception is thrown, DateTime.Parse happily converts this to the wrong date.

To do this, I use DateTime.ParseExact(userInput,"yyyy-MM-dd",currentCulture) .

So my question is not how to do this work (I have), but what happens to +01 or any + value? Am I missing something in the ISO standard?

+4
source share
1 answer

The only + in ISO8601 is part of the offset time, and it looks like in this case it is parsed this way. But as far as I know, all 3 parts of the date should have a valid value before the time offset.

I would recommend using DateTime.ParseExact(userInput,"yyyy-MM-dd",... (maybe even with InvariantCulture ).

DateTime.Parse accepts a huge amount of input and tries to best guess the intentions of users. This is similar to the case when he just guesses in an intricate way.

Example values ​​(first local PDT, 2 others with an explicit time offset):

 DateTime.Parse("1900-02" ).ToUniversalTime() // 2/ 1/1900 8:00:00 AM DateTime.Parse("1900-02+00").ToUniversalTime() // 2/ 1/1900 12:00:00 AM DateTime.Parse("1900-02+03").ToUniversalTime() // 1/31/1900 9:00:00 PM 

It seems that Parse essentially considers "YYYY-MM+0x" as "YYYY-MM-01T00:00+0x" .

+4
source

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


All Articles