How To Iterate Between Date Range

Introduction

While working on a project, I came across a scenario where I have to loop through each day of a calendar year. In this article, we will try to loop between date ranges. We will use IEnumerable interface and the "yield" keyword in C# to achieve this.

IEnumerable Interface

IEnumerable is the base interface for all non-generic collections that can be enumerated.

Namespace: System.Collection

Yield Keyword

With the help of "yield" keyword, we can read an element from the loop, return to the calling code, go back again to the same point from where it left the loop, and continue processing the loop for other records.

Now, let’s begin.

Create a function like below.

  1. public IEnumerable < DateTime > EachCalendarDay(DateTime startDate, DateTime endDate) {  
  2.     for (var date = startDate.Date; date.Date <= endDate.Date; date = date.AddDays(1)) yield  
  3.     return date;  
  4. }  

Consume the above function.

  1. DateTime StartDate = Convert.ToDateTime("15-08-2017");  
  2. DateTime EndDate = Convert.ToDateTime("20-08-2017");  
  3. foreach(DateTime day in EachCalendarDay(StartDate, EndDate)) {  
  4.     Console.WriteLine("Date is : " + day.ToString("dd-MM-yyyy"));  
  5. }  

Complete Program

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         DateTime StartDate = Convert.ToDateTime("15-08-2017");  
  4.         DateTime EndDate = Convert.ToDateTime("20-08-2017");  
  5.         foreach(DateTime day in EachCalendarDay(StartDate, EndDate)) {  
  6.             Console.WriteLine("Date is : " + day.ToString("dd-MM-yyyy"));  
  7.         }  
  8.     }  
  9.     public static IEnumerable < DateTime > EachCalendarDay(DateTime startDate, DateTime endDate) {  
  10.         for (var date = startDate.Date; date.Date <= endDate.Date; date = date.AddDays(1)) yield  
  11.         return date;  
  12.     }  
  13. }  

Summary

In this blog, we learned how we can iterate between date ranges.

I hope this will be helpful to some extent. Your thoughts and comments are always welcome.