Question

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?

Was it helpful?

Solution

I'm not sure this is any more elegant than what you already have, but how about:

  • Split the trimmed input by spaces
  • Do a TimeSpan.TryParse on the last piece
  • If this succeeds, check that the value of the resulting TimeSpan is non-negative, and less than a day

Do all that in addition to DateTime.TryParse on the string as a whole and you should have more confidence that there is a time component specified.

OTHER TIPS

I think you should split the user input, date in a textbox (or whatever) and time in another.

Another solution would be to use some kind of masked control, where you do not force d/m/y order, but you do enforce MM:SS, which is the same in every cuture.

Not quite the answer to the question, but hth

You can get the Date/Time formatting options for a culture from the CultureInfo.DateTimeFormat property. So, for example, to get the full date/time pattern for the current culture you would access:

CultureInfo.CurrentCulture.DateTimeFormat.FullDateTimePattern

For me, in the UK, this gives:

dd MMMM yyyy HH:mm:ss
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top