1

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.

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
H W
  • 2,556
  • 3
  • 21
  • 45

2 Answers2

2

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
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
-1

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)

H W
  • 2,556
  • 3
  • 21
  • 45
  • 1
    You need to use InvariantCulture or else this won't work as you expect it to – Matt Wilko Nov 26 '14 at 13:04
  • I think i am missunderstanding since the InvariantCulture depends on the english language, doesn't it? Thus i cannot pass InvariantCulture and still get the desired result? Still - the code above is just a general example taken from the link i provided. In my app i am passing a dedicated CultureInfo object which is used in several places. – H W Nov 26 '14 at 13:30
  • No the Invariant culture is essentially *no* specific culture or language. – Matt Wilko Nov 26 '14 at 13:47
  • 1
    You really want to do it per @MattWilko's answer. First, because of the Invariant culture thing; but also because `TryParse` tends to be orders of magnitude slower than `TryParseExact` -- see [here](http://stackoverflow.com/questions/179940/convert-utc-gmt-time-to-local-time/7905548#7905548) for details. – David Nov 26 '14 at 15:05