I have a string value that represents a date, and I want to parse it into a DateTime. Parsing should succeed, and ONLY succeed, if the format is valid in the specified culture.
Example:
Parsing "2/1/2020" should succeed in en-US culture, but fail in de-DE culture.
Parsing "1.2.2020" should succeed in de-DE culture, but fail in en-US culture.
My attempts using DateTime.TryParse
and DateTime.TryParseExact
did not give the results I want.
This returns false
, as expected, because the date is in en-US format, and the de-DE culture is used for parsing:
DateTime.TryParseExact("2/1/2020", "d", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)
but so does this because the "d" format requires leading zeroes for month/day values:
DateTime.TryParseExact("1.2.2020", "d", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)
I could use this instead, which returns true
:
DateTime.TryParse("1.2.2020", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)
But then so does this, which is bad especially because it returns the wrong date (Jan 2 instead of Feb 1):
DateTime.TryParse("2/1/2020", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)
How can I do this, without resorting to culture-specific date time format strings for each culture?