Search code examples
vb.netwql

Parsing different date strings into one format in VBNet


I'm trying to write a program that will pull a list of all installed windows updates and output the date of the most recent install. I'm hitting a wall due to the format outputted from the WMI query. My code is below:

        Dim dates = New List(Of String)
        Dim datearray = dates.ToArray()
        Try
        Dim searcher As New ManagementObjectSearcher( _
            "root\CIMV2", _
            "SELECT * FROM Win32_QuickFixEngineering")

        For Each queryObj As ManagementObject In searcher.Get()

        dates.Add((queryObj("InstalledOn")))

        Next
        Dim path As String = "C:\Users\Will\outputfile.txt"
        IO.File.WriteAllLines(path, dates)

I'm only writing out the output so I can check the dates, the problem I'm hitting is when trying to convert the array into dates it's throwing exceptions due to the date not being in the required format. For example, the output is:

12/7/2013
12/7/2013
12/7/2013
6/14/2013
10/7/2011
4/7/2011 

It's not fitting a required format to use a datetime.parse.

How can I convert the array so all dates are within the same format? (and please note that these dates are month/day/year and I could really do with them being day/month/year.

I've been reading through forums and trying a few different pieces of code that I've found but nothing has helped!

Just a thought but would there be something I can do with the WQL that would only export the latest update?

Thanks in advance :)


Solution

  • Use DateTime.ParseExact or DateTime.TryParseExact, you can specify any format you like:

    Dim provider As CultureInfo = CultureInfo.InvariantCulture
    Dim result as Date = Date.ParseExact("6/14/2013", "M/d/yyyy", provider)
    'result is now equal to a valid date - #6/14/2013 12:00:00 AM#