Paul Paul - 5 months ago 14
Vb.net Question

vb.net String was not recognized as a valid DateTime

I have the following function called setdateformat in my VB application.

Public Function SetDateFormat(ByVal ArrayInputString As String) As String

Dim FormattedDateString As String = ""
Dim DateInput As DateTime = DateTime.Parse(ArrayInputString)
FormattedDateString = DateInput.ToString("yyyy-MM-dd HH:mm:ss")
Return FormattedDateString

End Function


Its purpose is to format the date, however it keep falling over at the line
Dim DateInput As DateTime = DateTime.Parse(ArrayInputString)
. I have tried looking around online and investigating but to no avail. I have tried using dateTime.ParseExact but no luck.

Im really struggling to understand why this error is occurring for me to be honest, Hence the reason for this post so any help is much appreciated.

I have debugged the solution but to help anyone reading this understand the following values are being passed in the variables

ArrayInputString = 21/05/2015 09:29:41

Date Time Now = 05/21/2015 09:29:41

Any assistance wil be gladly taken on board

Paul

Answer

/ has a special meaning and functionality when it comes to date parsing: it means "replace me with the real date separator of the current culture". So i guess that your real date separator is something different like . or -.

If you look at the debugger it always uses invariant culture and not your curent culture which explains why you see dates like 5/21/2015 11:39:26 AM.

You could try multiple approaches:

Public Function SetDateFormat(ByVal inputString As String) As String
    Dim DateInput As DateTime
    Dim allowedCultures = {CultureInfo.CurrentCulture, CultureInfo.InvariantCulture}
    For Each culture In allowedCultures
        If Date.TryParse(inputString, culture, DateTimeStyles.None, DateInput) Then
            Return DateInput.ToString("yyyy-MM-dd HH:mm:ss")
        End If
    Next
    ' try ParseExact:
    Dim formats = {"yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss"}
    If Date.TryParseExact(inputString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, DateInput) Then
        Return DateInput.ToString("yyyy-MM-dd HH:mm:ss")
    Else
        Return Nothing
    End If
End Function

Documentation: The "/" Custom Format Specifier

Comments