views:

44

answers:

3

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?

A: 

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
Dan Diplo
Thanks for the input, but this won't help me solve the problem: To be user-friendly, I'd need to accept not only `dd MMMM yyyy HH:mm:ss` but also `dd MMMM yyyy HH:mm`, `d MMMM yyyy HH:mm:ss`, etc. So, I'd need something that (basically) accepts all formats that `DateTime.TryParse` accepts, with the additional restriction that a time component must be specified.
Heinzi
+1  A: 

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.

AakashM
+1  A: 

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

Daniel Dolz