Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

DateRange Class - C#

RSS
Modified on Tue, Nov 28, 2023, 8:47 AM by Administrator Categorized as Uncategorized

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;
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.