This is very weird. I have the following code:
Assert.AreEqual(new DateTime(2000, 1, 1), DateTime.ParseExact("2000", "yyyy", CultureInfo.InvariantCulture));
Assert.AreEqual(new DateTime(2000, 1, 1), DateTime.ParseExact("20000705", "yyyy", CultureInfo.InvariantCulture));
The first line passes, the second one fails with "System.FormatException: String was not recognized as a valid DateTime
".
I cannot shorten the string to be parsed to match the length of the format - it would work in this particular case, but this is part of a more generic method, and it would fail somewhere else. Any idea on why the second call fails?
[Edit] Ok, I was hoping it was parsing just as much of the input string as needed to satisfy the format.
I get a lot of strings in a lot of formats, and I have one method that accepts both and, after a bit of processing (I only get dates, so I replace "m" with "M" and "Y" with "y" and so on), I call DateTime.ParseExact
. The reason I cannot call DateTime.Parse
is because it doesn't allow for a format argument... I can get ddMMyyyy in one part of the program and yyyyddMM in another, there's no way for it to correctly figure it out.
[Edit 2] I guess it's my fault... I'll have to truncate the input when that issue arises. Fortunately I generally have all parts of the date in the format, this (just the year) is a rare occurence. Thanks for the help.