specifying CultureInfo in isDate() or Datetime.TryParse

1.5k Views Asked by At

I need to identify if a string is a date in format dd.mm.yyyy.

However the application is running on systems with different language settings. Thus using isDate or TryParse on a 'valid' string returns true on a german system (since those functions use CultureInfo.CurrentCulture) and return false on a system with i.e. english system settings.

Is there a function that checks if a string is a valid date with respect to a specified CultureInfo?

Of course i can always use regex to verify this, but i can't imagine that this is necessary.

2

There are 2 best solutions below

0
On BEST ANSWER

If you know the format of the string and this won't change you should use DateTime.TryParseExact using the InvariantCulture

Imports System.Globalization

Dim dateString As String = "31.12.1901"
Dim dateValue As Date
Dim dateFormat As String = "dd.MM.yyyy"

If DateTime.TryParseExact(dateString, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, dateValue) Then
    'In the format expected
Else
    'NOT in the format expected
End If
4
On

Seems like i missed an overload of the TryParse Method:

Dim myculture As New System.Globalization.CultureInfo("en-US")
myculture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy"
myculture.DateTimeFormat.LongDatePattern = "dd/MM/yyyy"

If DateTime.TryParse("27/10/2010", myculture, Globalization.DateTimeStyles.None, New DateTime) Then

'Currect Date

End If

works perfectly fine. (See http://forums.asp.net/t/1443698.aspx?in+ASP+NET+vb+IsDate+function+is+working+wrongly+ for details)