Obsidian Obsidian - 3 years ago 107
Vb.net Question

Return a default date with TryParseExact in .NET

Why does this function not return the default value?

If parsing fails a date of 1900-01-01 should be returned.

It instead returns 01/01/0001 which is the date defualt for .NET

Public Shared Function ParseDate(FieldName As Object) As Date
Dim ID As Date = "1900-01-01"

If TypeOf FieldName Is TextBox Then
If Date.TryParseExact(FieldName.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, ID) Then
ID = FieldName.Text
End If
End If

Return ID
End Function

Answer Source

You have misunderstood how DateTime.TryParse works. It doesn't return your passed DateTime as fallback value. An out parameter is not interested in your input argument. TryParse will assign the default value of DateTime which is MinValue to the out-parameter if it could not be parsed. That's documented.

When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

So you see it returns DateTime.MinValue if it could not parse successully.


But you should use the returned Boolean anyway to determine if it could be parsed:

Dim validDate = Date.TryParseExact(FieldName.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, ID)

The above function can be rewritten to:

Public Shared Function ParseDate(FieldName As Object) As Date
    If TypeOf FieldName Is TextBox Then
        Dim dt as Date
        If Date.TryParseExact(FieldName.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, dt) Then
            Return dt
        End If
    End If

    Return New Date(1900, 1, 1)
End Function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download