2

I'm new to using DateTime but I'm wondering if it is able to add every single day between two points to a list dynamically.

For example, my code looks like this:

{
  startTime = new DateTime(startYear, startMonth, startDay);
  endTime = new DateTime(endYear, endMonth, endDay);        
  TimeSpan elapsed = endTime.Subtract(startTime);               
  startString = startDay.ToString();
  elapsedString = elapsed.TotalDays.ToString();
}

Through this I can return the total amount of days between two points. However, elapsed.TotalDays.ToString(); only returns the total amount of days between two points. What I'm wondering is if it is possible to return every single day between two points and place it into a list?

Nishanth
  • 168
  • 3
  • 12
N0xus
  • 2,674
  • 12
  • 65
  • 126

3 Answers3

3

You can do this with Enumerable.Range

using System;
using System.Linq;

var totalDays = (int)endTime.Subtract(startTime).TotalDays;
var days = Enumerable.Range(0, totalDays)
                     .Select(n => startTime.AddDays(n))
                     .ToList();

Both start and enddates are included in the days list. Start by setting the range to start at zero, end by leaving n alone.

crthompson
  • 15,653
  • 6
  • 58
  • 80
3

i think you can iterate using for

list<int>Dates = new List<int>();

for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
  Dates.Add(date.Date);
}
Nishanth
  • 168
  • 3
  • 12
2

Give this a try, it should work:

int totalDays = endTime.Subtract(startTime).TotalDays as int;
List<DateTime> dates = new List<DateTime>(totalDays + 1); // using this constructor will make filling in the list more performant

dates.Add(startTime); // since you mentionned start and end should be included

for (var i = 1; i < totalDays; i++)
{
    dates.Add(startTime.AddDays(i));
}

dates.Add(endTime);
N0xus
  • 2,674
  • 12
  • 65
  • 126
Crono
  • 10,211
  • 6
  • 43
  • 75