Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of dates from StartDate to EndDate

Tags:

c#

lambda

linq

How can i get list of dates between start and end dates using linq or lambda expression.

DateTime StartDate = DateTime.Now;
DateTime EndDate = DateTime.Now.AddMonths(13);
List<DateTime> ListofDates = //Contains list of all dates only between start and end date.
like image 797
SOF User Avatar asked Dec 09 '25 13:12

SOF User


2 Answers

Enumerable.Range(0, (EndDate - StartDate).Days).Select(i => StartDate.AddDays(i))
like image 108
SLaks Avatar answered Dec 12 '25 03:12

SLaks


First of all, when you want Dates and not Datetimes you better use DateTime.Now.Date instead of just DateTime.Now

I've edited SLaks code so you can get the list of dates you want.

DateTime StartDate = DateTime.Now.Date;
DateTime EndDate = DateTime.Now.Date.AddMonths(13);
IEnumerable<double> daysToAdd = Enumerable.Range(0,
                                                (EndDate - StartDate).Days + 1)
                                            .ToList().ConvertAll(d => (double)d);
IEnumerable<DateTime> ListOfDates = daysToAdd.Select(StartDate.AddDays).ToList();

Note that I've added +1 in the enumerable so you can have both the start and end date (you didn't specify it)

like image 30
Odys Avatar answered Dec 12 '25 03:12

Odys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!