DateTime format one digit day not recognized

I need to read a String in the following format: "6102015" (meaning October 6th, 2015) and turn it into DateTime objects.

I tried the following code, which did not work:

DateTime.ParseExact("6102015", "dMyyyy", CultureInfo.CurrentCulture);

But when I tested the code using the date string with an extra 0, it worked.

DateTime.ParseExact("06102015", "dMyyyy", CultureInfo.CurrentCulture); // works correctly

Is there a way to read this date format without having to add the 0?

I thank you in advance for any help.

Jon Skeet
people
quotationmark

Is there a way to read this date format without having to add the 0?

Adding a 0 is the least of your worries, IMO. That takes one line of code.

Assuming you've got a copy of the database or something you can alter, effectively, I would:

  1. Create a field of a date/time type, or if you must use a string, do so but use an ISO-8601 format (yyyy-MM-dd)
  2. Parse all the values which are already 8 characters
  3. Parse all the values which are 6 characters by inserting two 0s (so abcccc becomes 0a0bcccc)
  4. For each remaining value, of the form abcyyyy:
    • Try parsing it as 0abcyyyy
    • Try parsing it as ab0cyyyy
    • If only one parse worked, store that result in the new column
  5. Now look at all the remaining rows (i.e. the ones you haven't populated with a "known good" value
    • You may be able to use other data (such as insertion order) to work out which is the "right" parse...
    • You may not - in which case you need to decide what to do

people

See more on this question at Stackoverflow