Search code examples
vb.netsplit

How can I split this filename to get the date only


How can I use VB.NET to split the below file names with one variable to extract the date portion of the filename?

I'm initially getting the filename from a path. Two examples:

Mozart - Cpt - 03 Aug 2024.xlsx
Mozart - 03 Aug 2024.xlsx

I have this code:

Din Filename as String = ""
Dim mDate as string = format(cdate(split(split(path.getfilename(Filename), "-")(1), ".xlsx")(0)),"yyyy/MM/dd")

The works for the second Mozart - 03 Aug 2024.xlsx example, but not the Mozart - Cpt - 03 Aug 2024.xlsx sample. How can I fix it?


Solution

  • You want to parse the last - part of the filename (without extension) to Date. So you can use Split and Enumerable.Last and Date.TryParseExact:

    Dim lastPart = Path.GetFileNameWithoutExtension(fileName).Split("-"c).Last()
    Date.TryParseExact(lastPart, "dd MMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, dt)
    

    Complete test code:

    Sub Main
        Dim FileNames() As String = {"Mozart - Cpt - 03 Aug 2024.xlsx","Mozart - 03 Aug 2024.xlsx"}
        For Each fileName In FileNames
            Dim lastPart = Path.GetFileNameWithoutExtension(fileName).Split("-"c).Last()
            Dim dt As Date
            If Date.TryParseExact(lastPart, "dd MMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, dt)
                Console.WriteLine(dt)
            End If
        Next
    End Sub
    

    http://dotnetfiddle.net/sjcWgr