How to convert multiple date formats to YYYY-MM-DD in VB.NET

1 Answer

0 votes
Imports System
Imports System.Globalization

' ********************************************************************************************
' Program: DateNormalizer
' Purpose: Convert many possible date formats into the canonical YYYY-MM-DD format.
' Notes:
'   - Uses .NET's built-in parsing capabilities with multiple formats and cultures.
'   - Demonstrates clean structure, modular functions, and clear commentary.
'   - Shows pitfalls, performance notes, and edge-case handling inside the code.
'   - Includes multiple test cases in Main.
'   - Avoids unnecessary allocations and uses efficient parsing patterns.
' ********************************************************************************************

Module DateNormalizer

    ' -----------------------------------------------------------------------------------------
    ' Function: NormalizeDate
    ' Purpose:
    '   Attempt to parse a date string using multiple known formats and fallback parsing.
    '   Returns a normalized YYYY-MM-DD string if successful; otherwise returns Nothing.
    '
    ' Implementation notes:
    '   - TryParseExact is used first with a curated list of formats.
    '   - If that fails, TryParse is used as a fallback for natural-language formats.
    '   - Using invariant culture avoids locale surprises.
    '   - The function is safe: no exceptions thrown for bad input.
    '   - Complexity: O(n) over the number of formats; extremely fast for typical usage.
    '   - Memory: minimal allocations; only strings and DateTime values.
    ' -----------------------------------------------------------------------------------------
    Private Function NormalizeDate(input As String) As String
        If String.IsNullOrWhiteSpace(input) Then
            Return Nothing
        End If

        Dim trimmed = input.Trim()

        ' Supported explicit formats. These cover many common separators and textual forms.
        ' The list is intentionally small but effective; adding more formats is trivial.
        Dim formats As String() = {
            "MM/dd/yyyy",
            "MM-dd-yyyy",
            "yyyy.MM.dd",
            "yyyy/MM/dd",
            "yyyy-MM-dd",
            "MMMM d, yyyy",
            "d MMM yyyy",
            "d MMMM yyyy",
            "MMM d, yyyy",
            "M/d/yyyy"
        }

        Dim dt As DateTime

        ' First attempt: TryParseExact with known formats.
        If DateTime.TryParseExact(trimmed,
                                  formats,
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.None,
                                  dt) Then
            Return dt.ToString("yyyy-MM-dd")
        End If

        ' Second attempt: TryParse for natural-language or unexpected-but-valid formats.
        ' This can parse many human-friendly formats but may be slower than TryParseExact.
        If DateTime.TryParse(trimmed,
                             CultureInfo.InvariantCulture,
                             DateTimeStyles.None,
                             dt) Then
            Return dt.ToString("yyyy-MM-dd")
        End If

        ' If both attempts fail, return Nothing to signal invalid input.
        Return Nothing
    End Function

    ' -----------------------------------------------------------------------------------------
    ' Sub: Main
    ' Purpose:
    '   Demonstrate the NormalizeDate function with multiple test cases, including edge cases.
    '   Shows how to handle invalid results gracefully.
    '
    ' Architecture notes:
    '   - Main acts as a simple test harness.
    '   - In real applications, this logic would be part of a service or utility class.
    '   - Error handling is explicit: Nothing means invalid date.
    ' -----------------------------------------------------------------------------------------
    Sub Main()
        Dim testInputs As String() = {
            "05/01/2024",
            "12-31-2023",
            "2024.02.09",
            "January 5, 2024",
            "2024/09/17",
            "2024-09-17",
            "25 Dec 2025",
            "6 Jan 2025",
            "Jan 7, 2025",
            "8 January 2025",
            "7/5/2026",
            "BadFormat",
            "Feb 30, 2024",
            "April 31, 2024"
        }

        Console.WriteLine("Date Normalization Results:")
        Console.WriteLine()

        For Each input In testInputs
            Dim normalized = NormalizeDate(input)
            If normalized IsNot Nothing Then
                Console.WriteLine($"Input: {input,-20}  →  {normalized}")
            Else
                Console.WriteLine($"Input: {input,-20}  →  INVALID DATE")
            End If
        Next

        Console.WriteLine()
        Console.WriteLine("Press ENTER to exit.")
        Console.ReadLine()
    End Sub

End Module


' 
' run:
'
' Input: 05/01/2024           →  2024-05-01
' Input: 12-31-2023           →  2023-12-31
' Input: 2024.02.09           →  2024-02-09
' Input: January 5, 2024      →  2024-01-05
' Input: 2024/09/17           →  2024-09-17
' Input: 2024-09-17           →  2024-09-17
' Input: 25 Dec 2025          →  2025-12-25
' Input: 6 Jan 2025           →  2025-01-06
' Input: Jan 7, 2025          →  2025-01-07
' Input: 8 January 2025       →  2025-01-08
' Input: 7/5/2026             →  2026-07-05
' Input: BadFormat            →  INVALID DATE
' Input: Feb 30, 2024         →  INVALID DATE
' Input: April 31, 2024       →  INVALID DATE
'

 



answered Sep 24 by avibootz
edited Sep 24 by avibootz
...