I've read this string from a file: 23/07/1998. This is a perfectly valid date string. It has no ambiguity, given those numbers there (appears) to be only one possible way to parse it.
DateTime.TryParse, on the other hand, tells me its invalid. I suspect this is due to my culture settings.
TryParse has variations that are rather complex, so I'm wondering if there's an easy way to parse this with "dd/MM/yyyy"?
3 Answers
TryParse doesn't know if your date is MM/dd/yyyy or dd/MM/yyyy. It's obvious to the observer only because we can deduce from the fact that there is no month 23. But it wouldn't know what 02/03/1998 was.
DateTime.ParseExact(dateString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Will tell it which format to use.
Dim iString As String = "01/12/1998"
Dim oDate As DateTime = DateTime.ParseExact(iString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
MsgBox(oDate.ToString())
Like already mentioned by dwilliss the regular DateTime.TryParse() method cannot distinguish between dd/MM and MM/dd, and operates only on a standard set of date time formats. To specify a different format use either DateTime.ParseExact() or DateTime.TryParseExact()
If you want a less annoying syntax you can create an extension method wrapping the DateTime.TryParseExact() method.
Imports System.Globalization
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()> _
Public Function TryParseDate(ByVal Input As String, ByVal Format As String, <Out()> ByRef Result As DateTime) As Boolean
Return DateTime.TryParseExact(Input, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, Result)
End Function
End Module
Now you can use it like this:
Dim DateString As String = "23/07/1998"
Dim ResultDate As DateTime = Nothing
If DateString.TryParseDate("dd/MM/yyyy", ResultDate) Then
MessageBox.Show("Success: " & ResultDate.ToString())
Else
MessageBox.Show("Input was not a valid date!")
End If