首页 > 解决方案 > 日期范围搜索中不显示相等日期

问题描述

当我设置结束日期时,例如 31.08.2018,没有找到包含 8 月 31 日的记录,但它们存在于 DB 中,直到 8 月 30 日为止。我需要一个带有每月第 31 天的日期显示。

模型中的日期

//...
public Nullable<System.DateTime> dt_corr { get; set; }
//...

控制器

public ActionResult Index(DateTime? startdate, DateTime? enddate, int? page)
{
   var samp = from s in db.Samples
              select s;

   if (startdate != null)  // also tried startdate.HasValue 
   {
      samp = samp.Where(s => s.dt_corr >= startdate); //also tried startdate.Value 
      ViewBag.StartDate  = startdate;
   }
   if (enddate != null)// also tried enddate.HasValue
   {
      samp = samp.Where(s => s.dt_corr <= enddate); // also tried enddate.Value , no difference
      ViewBag.EndDate = enddate;  
      {
         int pageSize = 10;
         int pageNumber = (page ?? 1);
         return View(sampl.ToPagedList(pageNumber, pageSize));
      }

看法

    //...
    @using (Html.BeginForm("Index", "Samples", FormMethod.Get))
    {
       <p>
          Date
          @Html.Label("StartDate", "Start Date:")
          <input class="startdate" id="startdate" name="startdate" type="date" value="">
          @Html.Label("EndDate", "Final Date:")
          <input class="enddate" id="enddate" name="enddate" type="date" value="">  // in the example class="startdate" too, no difference
          <input type="submit" value="Search"/>
      </p>
    }
    // ...
    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of 
    @Model.PageCount

    @Html.PagedListPager(Model, page => Url.Action("Index",
        new { page, startdate = ViewBag.StartDate, enddate = ViewBag.EndDate }))

标签: c#asp.net-mvcdatetime

解决方案


似乎在您的数据库中会有一条记录,dt_corr = "2018-08-31 12:33:32.130"并且您要与之比较的是enddate = "2018-08-31 00:00:00.000". 所以那些记录不会出现。

尝试如下。

samp = samp.Where(s => s.dt_corr != null && s.dt_corr.Value.Date <= enddate.Value.Date);

推荐阅读