0

I have the date 201944102446 which I'm trying to DateTime.TryParseExact. Note that this doesn't have the leading zeros for the date and the month.

I have tried the following.

DateTime.TryParseExact("201944102446", "yyyyMdhhmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedDateTime);

This doesn't parse the DateTime string correctly (gives me DateTime.MinValue). Can anyone shed some light here as to what I might be doing wrong?

Kavo
  • 543
  • 1
  • 6
  • 16
  • 2
    How do you expect the function to tell the difference between January 11 and November 1? – John Wu May 02 '19 at 00:42
  • If you can separate the Date parts (and the format string) with a space, it will parse it. – Jimi May 02 '19 at 00:51
  • I dont think this is possible, i mean you could strip the `yyyy`, and the `hhmmss`. but even then if you have 3 digits left its impossible to know what they are, in short someone has made a very bad design decision – TheGeneral May 02 '19 at 00:52
  • Other related posts: https://stackoverflow.com/q/26773534/447156 and https://stackoverflow.com/q/35229843/447156 and https://stackoverflow.com/q/26773534/447156 – Soner Gönül May 02 '19 at 05:57
  • [Here what .NET Team suggest for this situation](https://stackoverflow.com/a/26778076/447156) – Soner Gönül May 02 '19 at 05:59

1 Answers1

3

Using ParseExact with optional leading zeros can be ambiguous if there are not delimiters between the components. What would 2019111000000 represent?. Jan 11 or Nov 1?

I think if the parser hits a code with an optional leading zero, and sees more than one digit in the value, it tries to parse as if the number is two digits.

So it parses 2019 as the year, then tries to parse 44 as the month, which fails. It is not "smart" enough to know that 44 could not represent a valid month and deduce that it must represent a single digit month.

You could do some processing on your own, like taking off the year and time which are known widths and figuring out if either the month or day (or both) are two digits, but you still have the possibility of ambiguity with the example I give above. If there is any other context to your data (like it's in some order) you could make an educated guess about the month and day, but the built-in parser isn't that sophisticated.

D Stanley
  • 149,601
  • 11
  • 178
  • 240