Joseph Katzman
Joseph Katzman

Reputation: 2085

How can I do universal query for date range?

I'm using LINQ for getting list of objects which are in a specific date range. For example, I have current day in DateTime format: 21.05.2016 0:00:00 and I need to get news which were published after 1 day ago (5 day ago, 3 months ago, 1 year ago, 5 years ago) and until this moment. I did it the folowing way:

List<MyObject> data =
    DataDownloader.myList.Where(s => s.Date.Year >= fromDate.Year
                                     && s.Date.Month >= fromDate.Month
                                     && s.Date.Day >= fromDate.Day
                                     && s.Date.Year <= toDate.Year
                                     && s.Date.Month <= toDate.Month
                                     && s.Date.Day <= toDate.Day).ToList();

toDate is my current date. I find the fromDate by the following:

1 day:

fromDate = toDate;

5 days:

fromDate = toDate.AddDays(-5);

3 months:

fromDate = toDate.AddMonths(-3);

etc.

But I get only 2 news for 3 months. It's 21.04.2016 0:00:00 and 21.05.2016 0:00:00. So you know they differ only numbers of months because my current date is 21.05.2016. What's I do wrong? I should get much more news I know it.

Upvotes: 0

Views: 81

Answers (1)

Charles Mager
Charles Mager

Reputation: 26213

You're comparing each of the elements of a date, which isn't going to give you the right answer.

You're saying for the 'last 3 months' (from 21/02/2016 to 21/05/2016) that the day has to be between 21 and 21, the month between 2 and 5 and the year between 2016 and 2016

You're effectively searching for 21/02/2016, 21/03/2016, 21/04/2016 or 21/05/2016 rather than all dates between.

Just compare the date:

list.Where(x => x.Date >= fromDate && x.Date <= toDate).ToList();

Upvotes: 2

Related Questions