DateRange Class - C#

Overview

This article provides a C# class that can break a date range into segments.

Code

[DebuggerDisplay("{DisplayText}")]
public class DateRange
{
    public DateTime StartOn { get; set; }
    public DateTime EndOn { get; set; }
    public string DisplayText
    {
        get
        {
            return $"{StartOn:MM/dd/yy} - {EndOn:MM/dd/yy}";
        }
    }

}
public static class DateRangeExtensions
{
    public static List<DateRange> BreakIntoSegments(
        this DateRange dateRange,
        int daysPerSegment
        )
    {
        var result = new List<DateRange>();
        DateTime dt1 = dateRange.StartOn;
        DateTime dt2;

        do
        {
            dt2 = DateFunctions.Earlier(dateRange.EndOn, dt1.AddDays(daysPerSegment));

            result.Add(new DateRange { StartOn = dt1, EndOn = dt2 });

            dt1 = dt2.AddDays(1);

        } while (dt2 < dateRange.EndOn);

        return result;
    }
}


public static class DateFunctions
{
    public static DateTime Earlier(DateTime d1, DateTime d2)
    {
        return d1 < d2 ? d1 : d2;
    }

    public static DateTime Later(DateTime d1, DateTime d2)
    {
        return d1 > d2 ? d1 : d2;
    }
}