Checking if a user input is a valid date or a valid "date + time" is easy: .NET provides DateTime.TryParse
(and, in addition, VB.NET provides IsDate
).
Now, I want to check if the user entered a date including a time component. So, when using a German locale, 31.12.2010 00:00
should be OK, but 31.12.2010
shouldn't.
I know I could use DateTime.TryParseExact like this:
Dim formats() As String = {"d.M.yyyy H:mm:ss", "dd.M.yyyy H:mm:ss", _
"d.MM.yyyy H:mm:ss", "d.MM.yyyy H:mm:ss", _
"d.M.yyyy H:mm", ...}
Dim result = DateTime.TryParseExact(userInput, formats, _
Globalization.CultureInfo.CurrentCulture, ..., result)
but then I would hard-code the German format of specifying dates (day dot month dot year), which is considered bad practice and will make trouble should we ever want to localize our application. In addition, formats
would be quite a large list of all possible combinations (one digit, two digits, ...).
Is there a more elegant solution?