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); }
You can try the following: if ( (b[2] <= c[2]) && (b[2] >= a[2]) ) //comparing years if ( (b[1] <= c[1]) && (b[1] >= a[1]) ) //comparing months if ( (b[0] <= c[0]) && (b[0] >= a[0]) ) //comparing days // ...
To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.
The difference between two dates can be calculated in C# by using the substraction operator - or the DateTime. Subtract() method. The following example demonstrates getting the time interval between two dates using the - operator.
Number of days = monthDays[date[1]]. monthDays will store the total number of days till the 1st date of the month.
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); }
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With