Stephen Sugumar
Stephen Sugumar

Reputation: 545

C#: get database records within date range

I had asked a question yesterday where I must return Database records within a given Date Range. In the question yesterday I had stated that within the DB Table, the dates were in 'nvarchar' type, After contacting the DB admin.

the types have now been changed to type 'DateTime'

Thus, I am looking for a Linq expression to return DB records within a given Date Range. Previous Question Link: Return DB results within Date Range

Code:

public ActionResult timePeriod(string time)
{
    //Start: month, day, year End: month, day, year --> Numeric values
    string[] times = time.Split(',');                             
    string start = times[0] + " " + times[1] + " " + times[2];
    string end = times[3] + " " + times[4] + " " + times[5];

    var sDate = DateTime.Parse(start);
    var eDate = DateTime.Parse(end);

    //viewModel.Tasks = db.Tasks.   //Linq expression to return values withing range.
    viewModel.EngineerSkills = db.EngineerSkills.ToList();
    viewModel.Categories = db.TaskCategories.ToList();

    gatherInfo(viewModel);
    gatherXML();
    timeRestrictions(viewModel);
    gatherMapPositions(viewModel);

    return View("Index", viewModel);
}

Upvotes: 0

Views: 2036

Answers (3)

mybirthname
mybirthname

Reputation: 18127

//previous code
.....
var viewModelDates = viewModel.Where(p=>p.StartTime >=sDate && p.EndTime<=eDate);
return View("Index", viewModelDates.ToList());

You should make check where StartTime>=sDate and p.EndTime<=endTime. This should return you the correct values. I hope you have valid sDate and eDate.

Upvotes: 1

hame-dhib
hame-dhib

Reputation: 428

i dont now if i m understund your problem or no,try this code

var query = (from a in announcements
         where (a.Begins <= RightNow) && (a.Expires >= RightNow)
         select a).ToList();

Upvotes: 1

Please, try this:

viewModel.Tasks = db.Tasks.Where(s => DbFunctions.TruncateTime(s.StartTime) == DbFunctions.TruncateTime(sDate)).ToList();

Upvotes: 0

Related Questions