Andrea
Andrea

Reputation: 101

VB.Net - How can i tailor my function to read the date of the new filename structure?

Afternoon,

How can I tailor the below function in VB.net to pickup the first 8 characters of the second part of the filename in the array?

Private Function GetFormattedDateFromFileName(ByVal fileName As String) As String
    Dim parts() As String = fileName.Split("-")
    If parts.Length = 3 Then
        Dim dt As DateTime
        If DateTime.TryParseExact(parts(1), "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, dt) Then
            Return dt.ToString("MM/dd/yyyy")
        End If
    End If
    Return ""
End Function

I was using this function before because the filename would be split in 3 parts so this worked perfect for me. File name looked like below before:

542656-20130402-FTO Disclosure.pdf
548872-20120501-Funds a.pdf
848581-20110215-Alpha.pdf

Problem now is that the filename structure has been changed and will now be in 2 parts like so:

542656-20130402.pdf
548872-20120501.pdf
848581-20110215 Alpha.pdf
652162-20120711 a.pdf

So how would I go about to tailor the above function to still split the filename with the “-“ but instead of trying to parse the date exactly, for it to just look at the first 8 characters of the second part (being the date) and continue on as it has been with the rest of the code?

Kindly advise. A

Upvotes: 1

Views: 197

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564423

If you change your split call and length check to:

Dim parts() As String = fileName.Split("-"c, "."c, " "c)
If parts.Length > 2 Then

Then the existing code should work correctly on both versions.


Edit in response to comment:

In order to make this work on files like "12764-20120124b.pdf", you'll need to just extract the substring directly:

Private Function GetFormattedDateFromFileName(ByVal fileName As String) As String
    Dim parts() As String = fileName.Split("-")
    If parts.Length > 1 AndAlso parts(1).Length >= 8 Then
        Dim dt As DateTime
        Dim dtStr = parts(1).Substring(0, 8)
        If DateTime.TryParseExact(dtStr, "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, dt) Then
            Return dt.ToString("MM/dd/yyyy")
        End If
    End If
    Return ""
End Function

Upvotes: 2

Related Questions