4

I faced with issue related to DateTime.ParseExact. Cannot parse string with 1 digit for month.

//this works fine with 2 digits for month
DateTime.TryParseExact("030405", "MMddyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);

//this works also fine with 1 digit for month but with hyphen or space
DateTime.TryParseExact("3-04-05", "M-dd-yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
DateTime.TryParseExact("3 04 05", "M dd yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);

//but this DOES NOT work with 1 digit without hyphen
DateTime.TryParseExact("30405", "Mddyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);

For me it looks illogically.

user2216
  • 809
  • 1
  • 8
  • 24
  • 1
    Why can't you add s leading zero by doing PadLeft(6, "0") ? – Shai Aharoni Jul 21 '16 at 11:19
  • @ShaiAharoni Sure I can, and I've already done this for my purpose. But I'm just curious why it doesn't work. – user2216 Jul 21 '16 at 11:22
  • It's very very strange. I would post it as an open issue in the .NET framework. I Guess you need to look at the function's implementation to realy understand why you get this error. – Shai Aharoni Jul 21 '16 at 11:27
  • Possible duplicate - http://stackoverflow.com/questions/2016206/net-why-is-tryparseexact-failing-on-hmm-and-hmmss – ChrisF Jul 21 '16 at 12:51
  • 1
    From the OP's answer to that question is appears that even though you've specified that you want a single digit month it grabs two digits to try to parse which then doesn't leave enough data for other format specifiers. – ChrisF Jul 21 '16 at 12:54
  • @ChrisF thanks. I just thought about it and such logic, and it seems to be very logically. It works like that for `ToString(format)` and it should works for parsing in the same way. – user2216 Jul 21 '16 at 13:46

0 Answers0