Consider the following code for parsing a date. (Note that I'm on the EN-gb locale):
const DateTimeStyles DATE_TIME_STYLES = DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowWhiteSpaces;
DateTime dt;
// Current culture for this example is "EN-gb".
if (DateTime.TryParse("31/12", CultureInfo.CurrentUICulture, DATE_TIME_STYLES, out dt))
Console.WriteLine("Parsed correctly"); // Do not want!
else
Console.WriteLine("Did not parse correctly.");
I intentionally omit the year. However, it TryParse()will analyze this without any errors and will replace the current year.
I would like to force the user to enter ALL date components (using their local format), so I would like the parsing described above to fail, or to detect that the user didn not enter the year.
I really don't want to use it DateTime.TryParseExact(), because then I will need to add code to indicate all the different valid formats for all supported locales, which is non-trivial and likely error prone. I suspect this may be my only reasonable option.
Does anyone have any ideas? (Someone here at work has already implemented a “solution”, which implies the impossibility of the current year, which is clearly not a good solution ...)
source
share