Retrieve data based on two date values ​​filtered by month

I have a list of events, each event has two dates; start date and end date. I want to create a filter by month. How to return dates that vary between the month that the user selects? for example, let's say that the user selects the month of October, I want to return all the events that are in this month.

I used this to get dates that vary between today's dates, but are now stuck on how to get the range between the months.

DateTime dateToCheck = DateTime.Today.Date; DateTime startDate = DateTime.Parse(item["Start Time"].ToString()); DateTime endDate = DateTime.Parse(item["End Time"].ToString()); foreach (SPListItem item in collection) { if (startDate <= dateToCheck && dateToCheck < endDate) { ListBox1.Items.Add(item["EventTitle"].ToString()); } } 
+5
source share
2 answers
 // set up dummy data var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now}; int month = GetMonth(); // get result var result = dates.Where(date => date.Month == month); 

EDIT: if you need to make sure the dates have the correct year, use

 var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now}; int year = GetYear(); int month = GetMonth(); var result = dates.Where(date => date.Year == year && date.Month == month); 

Of course, you can get year / month numbers, as well as a list of dates from anywhere.

EDIT2: if you get a DateTime object as an input file, change accordingly:

 var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now}; var input = GetDateTime(); var result = dates.Where(date => date.Year == input.Year && date.Month == input.Month); 
+3
source

You can still use your code with slight modifications. As the start date, you must select 00:00 on the 1st of the month, and as the end date you should use 00:00 on the 1st of the next month. In the case of October 2015, it will be: 1 Oct 2015 <= date < 1 Nov 2015 .

 int year = 2015; int month = 10; DateTime dateToCheck = DateTime.Today.Date; DateTime startDate = new DateTime(year, month, 1); DateTime endDate = startDate.AddMonths(1); foreach (SPListItem item in collection) { if (startDate <= dateToCheck && dateToCheck < endDate) { ListBox1.Items.Add(item["EventTitle"].ToString()); } } 
0
source

All Articles