How to get dates between two dates in C#

2020-06-08 03:18发布

I would like to get dates between two dates. Instead of expected 9 different dates, I get 875287 and run out of memory. What would be the problem with the code below?

StartDate value is 01/04/2016 00:00:00

EndDate value is 10/04/2016 00:00:00

var selectedDates = new List<DateTime?>();
for (var date = StartDate; date <= EndDate; date.Value.AddDays(1))
{
    selectedDates.Add(date);
}

标签: c# linq datetime
5条回答
ら.Afraid
2楼-- · 2020-06-08 04:03

LINQ solution (let's generate selectedDates):

  var selectedDates = Enumerable
    .Range(0, int.MaxValue)
    .Select(index => new DateTime?(StartDate.AddDays(index)))
    .TakeWhile(date => date <= EndDate)
    .ToList();
查看更多
Luminary・发光体
3楼-- · 2020-06-08 04:05

Decided to change it up with a do/while

var selectedDates = new List<DateTime?>();
DateTime? StartDate = DateTime.Parse("01/04/2016 00:00:00");
DateTime? EndDate = DateTime.Parse("10/04/2016 00:00:00");

do
{
    selectedDates.Add(StartDate);
    StartDate = StartDate.Value.AddDays(1);
}while(StartDate < EndDate);
查看更多
▲ chillily
4楼-- · 2020-06-08 04:06

A shorter notation using Linq's Range method uses the ability to already figure out the number of days using the TimeSpan.Days property after subtracting start from end.

Assuming the start is before end you'd end up with:

DateTime StartDate = new DateTime(1979, 10, 4);
DateTime EndDate = new DateTime(2016, 10, 4);

var dates = Enumerable.Range(0, (EndDate - StartDate).Days + 1)
    .Select(day => StartDate.AddDays(day))

If you need it to be Nullable, add:

    .Cast<DateTime?>()

If you need this to be a List, add:

    .ToList()

It's probably quite a bit more efficient than the other LINQ based solution.

查看更多
女痞
5楼-- · 2020-06-08 04:21

You aren't assigning the value of date.Value.AddDays(1) to anything, so it ends up in an infinite loop. You'd need to change your code so that date is set to the result of AddDays.

for (var date = StartDate; date <= EndDate; date = date.AddDays(1))
{
    selectedDates.Add(date);
}
查看更多
干净又极端
6楼-- · 2020-06-08 04:23

As far as I can see, since AddDays method returns a new instance of a DateTime, it does not change the current instance since DateTime is immutable.

Looks like your date is DateTime?, you can change this part as;

for (var date = StartDate; date <= EndDate; date = date.Value.AddDays(1))
{
    selectedDates.Add(date);
}

As usr pointed, this might be affected on DST. You might wanna check Dmitry's answer as well.

查看更多
登录 后发表回答