Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,401 questions

56,365 answers

573 users

How to sort a list of string‑based dates in C#

1 Answer

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

/*
    Program goal:
    -------------
    Sort a list of date strings in the format "YYYY-MM-DD".

    Approach:
      1. Parse each string into DateTime using ParseExact.
      2. Sort using List.Sort(), which uses an efficient O(n log n) algorithm.
      3. Convert back to strings and print results.

    Architecture notes:
    -------------------
    - Parsing is isolated in a dedicated function for clarity and testability.
    - Sorting uses the built-in TimSort implementation (stable, efficient).
    - Error handling: invalid formats are detected and reported.
    - Edge cases: malformed strings, invalid ranges, leap years.
    - Performance: DateTime parsing is fast; sorting is O(n log n).
    - Memory: minimal; only a list of small objects.
    - Security: no unsafe operations; uses immutable DateTime.
*/

class SortDatesProgram
{
    // Strict ISO 8601 formatter
    private static readonly string IsoFormat = "yyyy-MM-dd";
    private static readonly CultureInfo Culture = CultureInfo.InvariantCulture;

    /*
        Parse a date string into DateTime.
        Throws an exception with a clear message on failure.
    */
    public static DateTime ParseDate(string s)
    {
        try
        {
            return DateTime.ParseExact(s, IsoFormat, Culture, DateTimeStyles.None);
        }
        catch (FormatException)
        {
            throw new ArgumentException("Invalid date: " + s);
        }
    }

    /*
        Sort a list of date strings.
        Returns a new sorted list; does not mutate the input.
    */
    public static List<string> SortDates(List<string> dates)
    {
        var parsed = new List<DateTime>(dates.Count);

        // Parse all dates; fail fast on invalid input.
        foreach (var s in dates) {
            parsed.Add(ParseDate(s));
        }

        // Sort using natural DateTime ordering.
        parsed.Sort();

        // Convert back to strings.
        var result = new List<string>(parsed.Count);
        foreach (var d in parsed) {
            result.Add(d.ToString(IsoFormat));
        }

        return result;
    }

    /*
        Helper to print a list of strings.
    */
    public static void PrintList(List<string> list)
    {
        foreach (var s in list) {
            Console.WriteLine("  " + s);
        }
    }

    /*
        Helper to run a named test case.
    */
    public static void RunTest(string name, List<string> dates)
    {
        Console.WriteLine();
        Console.WriteLine("=== " + name + " ===");

        try
        {
            var sorted = SortDates(dates);
            PrintList(sorted);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }

    /*
        Main program with multiple test cases.
    */
    static void Main()
    {
        // Basic chronological order
        RunTest("Basic chronological order",
            new List<string> {
                "2024-01-05",
                "2023-12-31",
                "2024-01-01",
                "2022-07-15"
            });

        // Already sorted input
        RunTest("Already sorted input",
            new List<string> {
                "2020-01-01",
                "2020-01-02",
                "2020-01-03"
            });

        // Leap year edge cases
        RunTest("Leap year edge cases",
            new List<string> {
                "2020-02-29",
                "2019-02-28",
                "2021-03-01"
            });

        // Invalid date detection
        RunTest("Invalid date detection",
            new List<string> {
                "2024-13-01",   // invalid month
                "2024-02-30",   // invalid day
                "not-a-date"    // malformed
            });
    }
}


/*
run:

=== Basic chronological order ===
  2022-07-15
  2023-12-31
  2024-01-01
  2024-01-05

=== Already sorted input ===
  2020-01-01
  2020-01-02
  2020-01-03

=== Leap year edge cases ===
  2019-02-28
  2020-02-29
  2021-03-01

ERROR!
=== Invalid date detection ===
Error: Invalid date: 2024-13-01

*/

 



answered Sep 23 by avibootz
...