DateTime: Requires the user to enter a time component

Validating whether an input date or a valid "date + time" is correct: .NET provides DateTime.TryParse

(and also VB.NET provides IsDate

).

Now I want to check if the user is entered on a date including the time component. So when using the German language it 31.12.2010 00:00

should be ok but 31.12.2010

shouldn't be.

I know that 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 day dot month dot year format, which is considered bad practice and will cause problems if we ever want to localize our application. In addition, there formats

will be a rather large list of all possible combinations (one digit, two digits, ...).

Is there a more elegant solution?

+2


a source to share


3 answers


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

  • Separate truncated input with spaces
  • Do TimeSpan.TryParse

    on the last part
  • If this succeeds, make sure that the resulting value is TimeSpan

    non-negative and less than a day


Do all of this in addition to DateTime.TryParse

for the string as a whole, and you need more confidence that the specified temporal component is specified.

+2


a source


I think you should separate the user input, the date in the textbox (or whatever), and the time in the other.

Another solution would be to use some kind of masked control, where you don't enforce the d / m / y order, but you enforce MM: SS, which is the same for every cuture.



Not really an answer to the question, but hth

+1


a source


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

CultureInfo.CurrentCulture.DateTimeFormat.FullDateTimePattern

      

For me in the UK this gives:

dd MMMM yyyy HH:mm:ss

      

0


a source







All Articles