How to get all dates between 2 dates in C#

1 Answer

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

public class CSharpMonoDateRangeGenerator
{

    /// <summary>
    /// Returns all dates between two dates (inclusive).
    /// </summary>
    /// <param name="startDate">The first date in the range.</param>
    /// <param name="endDate">The last date in the range.</param>
    /// <returns>An enumerable sequence of dates.</returns>
    public static IEnumerable<DateTime> GetDatesBetween(
        DateTime startDate,
        DateTime endDate) {
        // Normalize to date-only values (remove time component)
        startDate = startDate.Date;
        endDate = endDate.Date;
    
        // Validate input
        if (startDate > endDate)
            throw new ArgumentException("startDate cannot be greater than endDate.");
    
        // Yield each date in the range
        for (DateTime date = startDate; date <= endDate; date = date.AddDays(1)) {
            yield return date;
        }
    }

    public static void Main()
    {
        DateTime start = new DateTime(2026, 2, 26);
        DateTime end   = new DateTime(2026, 3, 2);

        foreach (DateTime date in GetDatesBetween(start, end)) {
            Console.WriteLine(date.ToString("yyyy-MM-dd"));
        }
    }
}


/*
run:

2026-02-26
2026-02-27
2026-02-28
2026-03-01
2026-03-02

*/

 



answered 4 days ago by avibootz
...