How to convert multiple date formats to YYYY-MM-DD in C#

1 Answer

0 votes
using System;
using System.Globalization;
using System.Collections.Generic;

/*
    Program: DateNormalizer (C#)
    Purpose:
        Convert many possible date formats into the canonical YYYY-MM-DD format.

    Notes:
        - Uses modular functions for clarity and maintainability.
        - Uses TryParseExact first for predictable parsing, then TryParse as a fallback.
        - Includes commentary on pitfalls, performance, memory, and edge cases.
        - Demonstrates multiple test cases in Main.
        - Avoids exceptions for invalid input; returns null instead.
        - Uses only standard library features.
*/

public static class 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 null.
    //
    // Implementation notes:
    //     - TryParseExact is deterministic and fast for known formats.
    //     - TryParse handles natural-language formats but is slower and more permissive.
    //     - InvariantCulture avoids locale-dependent surprises.
    //     - Complexity: O(n) over the number of formats; trivial for typical usage.
    //     - Memory: minimal allocations (strings + DateTime).
    // -----------------------------------------------------------------------------------------
    public static string NormalizeDate(string input)
    {
        if (string.IsNullOrWhiteSpace(input))
            return null;

        string trimmed = input.Trim();

        // Supported formats. This list can be extended easily.
        // These formats cover common separators and textual month names.
        string[] formats =
        {
            "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"
        };

        DateTime dt;

        // First attempt: exact formats.
        if (DateTime.TryParseExact(trimmed, formats, CultureInfo.InvariantCulture,
                                   DateTimeStyles.None, out dt))
        {
            return dt.ToString("yyyy-MM-dd");
        }

        // Second attempt: fallback natural-language parsing.
        if (DateTime.TryParse(trimmed, CultureInfo.InvariantCulture,
                              DateTimeStyles.None, out dt))
        {
            return dt.ToString("yyyy-MM-dd");
        }

        // Invalid or unsupported format.
        return null;
    }

    // -----------------------------------------------------------------------------------------
    // Main: Test harness
    // Purpose:
    //     Demonstrate NormalizeDate with multiple test cases, including invalid formats.
    //
    // Architecture notes:
    //     - In production, this logic would be part of a service or utility class.
    //     - Error handling is explicit: null means invalid date.
    //     - Tests include valid, ambiguous, and invalid formats.
    // -----------------------------------------------------------------------------------------
    public static void Main()
    {
        var testInputs = new List<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:\n");

        foreach (var input in testInputs)
        {
            string normalized = NormalizeDate(input);
            if (normalized != null)
            {
                Console.WriteLine($"Input: {input,-20} → {normalized}");
            }
            else
            {
                Console.WriteLine($"Input: {input,-20} → INVALID OR UNSUPPORTED FORMAT");
            }
        }
    }
}



/*
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 OR UNSUPPORTED FORMAT
Input: Feb 30, 2024         → INVALID OR UNSUPPORTED FORMAT
Input: April 31, 2024       → INVALID OR UNSUPPORTED FORMAT

*/

 



answered Sep 24 by avibootz
...