To support the other two solutions I thought a worked example might be in order
This function will return a value of True if the conversion was successful and outDate will be the Date. outDate will (usually) be set to 01/01/01 if the function returns False - do not rely on this
Private Function DateExample(ByVal inDate As String, ByVal culture As System.Globalization.CultureInfo, ByRef outDate As Date) As Boolean
Dim itWorked As Boolean = Date.TryParseExact(inDate, "d", culture, System.Globalization.DateTimeStyles.None, outDate)
Return itWorked
End Function
The function uses the
TryParseExact [
^]method to try to convert a date represented by a string using the "culture" settings defined. Note the lower-case
d
- that means I'm using a "short date" pattern... here is the
list of standard patterns
[
^]
Let's call that function ...
Private Function MessageToDisplay(ByVal inDate As String, ByVal inCulture As String) As String
Dim culture As System.Globalization.CultureInfo = New System.Globalization.CultureInfo(inCulture)
Dim aDate As Date
Dim itWorked As Boolean = DateExample(inDate, culture, aDate)
Dim retMsg As String
If itWorked Then
retMsg = "Date " + inDate + " with Culture " + inCulture + " = " + aDate.ToString(culture)
Else
retMsg = "Invalid Date " + inDate + " or culture " + inCulture
End If
Return retMsg
End Function
This function takes the required date represented as a string, and which culture we want the results in (i.e. format). Here is the
list of language codes avaiable[
^]. The function will return a message which will be different depending on whether or not the date could be provided in that culture.
Finally, here are some examples ...
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim USDate As String = "05/30/2014"
Dim USCulture As String = "en-US"
Dim UKDate As String = "30/05/2014"
Dim UKCulture As String = "en-GB"
MessageBox.Show(MessageToDisplay(USDate, USCulture))
MessageBox.Show(MessageToDisplay(UKDate, USCulture))
UKDate = "05/03/2014"
MessageBox.Show(MessageToDisplay(UKDate, USCulture))
End Sub