Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data based on two dates values filtered by month

Tags:

c#

asp.net

I have list of events, each event has two dates; start date and end date. I want to create a filter by months. How do I return dates that ranges between a month that a user selects? for example, lets say the user selects month October, I want to return all events that are within this month.

I have used this to get the dates that ranges between todays date but now stuck on how to get the range between a month.

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());
    } 
}
like image 508
ssss Avatar asked Oct 19 '22 05:10

ssss


1 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 as well, 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 the year/month numbers as well as the date-list from wherever.

EDIT2: if you get a DateTime object as input modify 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);
like image 146
sara Avatar answered Oct 31 '22 11:10

sara