String and Date Convert Process?


Jul 20, 2009
Programming Experience
Hey folks,

I'm new to these forums but am really enjoying reading the various posts. I have a question regarding string to date converting.

I have the following string from a file I need to convert to a valid DATE in VB, but I am unable to with the attempt's I have tried.

The date is: "Thu Dec 13 10:00:06 2007"

So I am assuming it is something like this in VB: "ddd MMM dd hh:mm:ss yyyy"

The code I am using is the following to test against an array to see if the date is encountered, once it is I want it to convert it to a VB based Date.

The arrPADate is an array with the value of a split string that looks like the following:

"MSVS01,Thu Dec 13 10:00:06 2007,NIC1,Intel(R) PRO/1000 MT Server Adapter,Intel(R)"

This grabDATE sub is called from within a FOR loop as it's testing each line of the file for a DATE. So the value being passed to it (strRawVal) is a string like the example above.

Private Sub grabDATE_PA(ByVal strRawVal_PA As String)
        Dim arrPADate() = strRawVal_PA.Split(",")
        Dim strExtractDATE As String = ""
        For intDummy As Integer = 0 To arrPADate.Length
            If FormatDateTime(arrPADate(intDummy), "ddd MMM dd hh:mm:ss yyyy") Then
                Console.WriteLine("Found Date/Time field in column: " & intDummy & " of value: " & arrPADate(intDummy))
            End If
    End Sub

Thanks in advance for any assistance,


VB.NET Forum Moderator
Staff member
Aug 17, 2004
Sydney, Australia
Programming Experience
First up, the FormatDateTime function is for converting a Date to a String, not a String to a Date.

Secondly, if you do need to convert a Date to a String then don't use FormatDateTime anyway. Use the Date's own ToString method or else String.Format.

As for how to convert a String to a Date, you would use the Parse, ParseExact, TryParse or TryParseExact method of the Date type. In your case you're you'd use TryParseExact. You'd use a Try method because you are not 100% guaranteed that the conversion will succeed as the data file may not contain valid data. You'd use an Exact method because you're string is in a non-standard format so you need to specify a custom format.

Finally, there a couple of potential issues with your format string:
"ddd MMM [B][U][COLOR="Red"]dd[/COLOR][/U][/B] [B][U][COLOR="Blue"]hh[/COLOR][/U][/B]:mm:ss yyyy"
The "dd" part could be an issue because it will only match double-digit days. That's fine for 10 or greater but what will your string look like for 9 or less? That format string will match 09, 08, 07, etc. but it will not match 9, 8, 7, etc. The other issue is the hour. I see no sign of an AM/PM indicator in your string so I assume your times will be in 24-hour format, but "hh" is for 12-hour time. You need to use "HH" for 24-hour time.
Top Bottom