Skip to content

Instantly share code, notes, and snippets.

@colinbreame
Forked from crmorgan/DateRange.cs
Last active June 2, 2019 22:23
Show Gist options
  • Save colinbreame/aa0c63c2dfcfdefcb898445432b05124 to your computer and use it in GitHub Desktop.
Save colinbreame/aa0c63c2dfcfdefcb898445432b05124 to your computer and use it in GitHub Desktop.
A c# class that represents a date range data structure.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Utils
{
/// <summary>
/// Represents a range of dates.
/// </summary>
public struct DateRange : IEnumerable<DateTime>
{
/// <summary>
/// Initializes a new instance of the <see cref="DateRange" /> structure to the specified start and end date.
/// </summary>
/// <param name="startDate">First date in the date range.</param>
/// <param name="endDate">Last date in the date range.</param>
public DateRange(DateTime startDate, DateTime endDate)
{
Start = startDate;
End = endDate;
}
/// <summary>
/// Gets the start date component of the date range.
/// </summary>
public DateTime Start { get; private set; }
/// <summary>
/// Gets the end date component of the date range.
/// </summary>
public DateTime End { get; private set; }
/// <summary>
// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns></returns>
public IEnumerator<DateTime> GetEnumerator()
{
for (DateTime date = Start; date <= End; date = date.AddDays(1))
{
yield return date;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets the number of whole days in the date range.
/// </summary>
public int Days
{
get { return (End - Start).Days + 1; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment