Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop between two dates

Tags:

I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and ending with the selected end date, obviously including all of the dates inbetween, regardless of how many days are inbetween the selected start and end dates.

Below I have the beginning of the method which takes the date strings and converts them into DateTime variables so that I can make use of the DateTime calculation functions. However, I cannot seem to work out how to calculate all of the dates inbetween the start and end date? Obviously the first stage is to subtract the start date from the end date, but I cannot calculate the rest of the steps.

Help appreciated greatly,

kind regards.

public void DTCalculations() { List<string> calculatedDates = new List<string>(); string startDate = "2009-07-27"; string endDate = "2009-07-29";  //Convert to DateTime variables DateTime start = DateTime.Parse(startDate); DateTime end = DateTime.Parse(endDate);  //Calculate difference between start and end date. TimeSpan difference =  end.Subtract(start);  //Generate list of dates beginning at start date and ending at end date. //ToDo: } 
like image 626
Goober Avatar asked Jul 29 '09 09:07

Goober


People also ask

How do I iterate over a date?

We can use the date_range() function method that is available in pandas. It is used to return a fixed frequency DatetimeIndex. We can iterate to get the date using date() function.


Video Answer


1 Answers

static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end) {     for(var day = start.Date; day <= end; day = day.AddDays(1))         yield return day; } 

Edit: Added code to solve your particular example and to demonstrate usage:

var calculatedDates =      new List<string>     (         AllDatesBetween         (             DateTime.Parse("2009-07-27"),             DateTime.Parse("2009-07-29")         ).Select(d => d.ToString("yyyy-MM-dd"))     ); 
like image 168
Matt Howells Avatar answered Sep 19 '22 05:09

Matt Howells