简体   繁体   中英

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);
}

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

var query = (from a in announcements
         where (a.Begins <= RightNow) && (a.Expires >= RightNow)
         select a).ToList();
//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 .

请尝试以下方法:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM