Linq to Get Values within date 没有带来正确的价值

Linq to Get Values within date Not bringing correct value

我有这个 Linq 查询,我想用它来列出具有日期范围的项目。

代码如下:

[HttpPost]
    public JsonResult AjaxMethod(string search, DateTime startDate, DateTime endDate)
    {
        var stDate = startDate.Date;
        var enDate = endDate.Date;
        var str = search;
       
        List<LoanAccount> loanAccounts  = (from loanCustomer in db.LoanAccounts
                                           where (loanCustomer.Account_Number.Contains(search) || search == null) 
                                           && (loanCustomer.Date_Opened >= stDate && loanCustomer.Date_Opened <= enDate)
                                           select loanCustomer).ToList();
        return Json(loanAccounts);
    }

如果 stdate 是 23/01/2021,endate 是 23/01/2021,它不会 return 那一天的值。如果我将 enDate 更改为 24/01/2021,它会带来 23/01/2021 的数据,而不会包含 24/01/2021 的数据。是不是我漏了什么?

23-01-2021 等同于 23-01-2021 00:00:00。因此比较 23-01-2021 14:00:00 <= 23-01-2021 将是 false.

换句话说,日期范围 23-01-202123-01-2021 不是一个范围,因为开始 (23-01-2021 00:00:00) 和结束 (23-01-2021 00:00:00) 是相同的。

相反,您需要将结束日期晚一天,然后只取严格小于结束日期的所有内容。所以范围是 23-01-202124-01-2021,本质上是 23-01-2021 00:00:0024-01-2021 00:00:00

因此您的解决方案应该是:

var stDate = startDate.Date;
var enDate = endDate.Date.AddDays(1);
var str = search;

List<LoanAccount> loanAccounts  =
    (from loanCustomer in db.LoanAccounts
    where (loanCustomer.Account_Number.Contains(search) || search == null)
    //                          Notice the "strictly less" comparison  v
    && (loanCustomer.Date_Opened >= stDate && loanCustomer.Date_Opened < enDate)
    select loanCustomer).ToList();

DateDiffDay 函数计算开始日期和结束日期之间的天数。 所以你可以试试这个:


 where (loanCustomer.Account_Number.Contains(search) || search == null)
       && EF.Functions.DateDiffDay(stDate, loanCustomer.Date_Opened)>=0 
       && EF.Functions.DateDiffDay(loanCustomer.Date_Opened, enDate) >=0