Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dates between two dates in C#

Tags:

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); } 
like image 582
Naughty Ninja Avatar asked Apr 22 '16 08:04

Naughty Ninja


People also ask

How do you check if a date is between two dates in C?

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 // ...

How do you calculate days between two dates?

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.

How do I get the difference between two dates in C #?

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.

How do I calculate the number of days between two dates in C++?

Number of days = monthDays[date[1]]. monthDays will store the total number of days till the 1st date of the month.


2 Answers

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); } 
like image 170
DoctorMick Avatar answered Sep 22 '22 06:09

DoctorMick


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(); 
like image 30
Dmitry Bychenko Avatar answered Sep 22 '22 06:09

Dmitry Bychenko