Datetime. Tryparse Fails for Perfectly Valid Dates

Datetime. Tryparse Fails for Perfectly Valid Dates

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"?

0

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.

2
Dim iString As String = "01/12/1998"
Dim oDate As DateTime = DateTime.ParseExact(iString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
MsgBox(oDate.ToString())
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.