Reputation: 2724
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?
Upvotes: 2
Views: 64
Reputation: 15865
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.
Upvotes: 3
Reputation: 10478
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);
Upvotes: 2
Reputation: 168
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);
}
Upvotes: 3