Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

c# - Search by Date doesnt retrive correct data

I make a search function to search field by Date, like DateTo and DateFrom. I create in Model field of DataTime Date

[Required]
    [Display(Name = "Date and Time")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date)]
    public DateTime DateAndTime { get; set; }

In Controller I create action for search

public IActionResult Index(string search)
        {
            IEnumerable<AdmissionPacients> admissionPatient = _db.AdmissionPacients
                .Include(u=>u.Patient)
                .Include(d=>d.Doctor);


            if(!string.IsNullOrEmpty(search))
            {
                if(DateTime.TryParse(search,out var dateTime))
                {
                    admissionPatient = admissionPatient.Where
                         (x => x.DateAndTime.ToShortDateString() == dateTime.ToShortDateString()).ToList();
                }
            }

            return View(admissionPatient);
        }

One think here is If I put date like 1/22/2021 - 01/31/2021 I didn't get exactly what I expect as uoutput. I expect in output to get three records but I get two records

enter image description here

enter image description here

Any idea guys where the problem could be ? Since I check a couple of think starting from add .FirstOrDefault() and using Select() but nothink works ?

question from:https://stackoverflow.com/questions/65849317/search-by-date-doesnt-retrive-correct-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use this code:

if(DateTime.TryParse(search,out var dateTime))
                {
                    admissionPatient = admissionPatient.Where
                         (x => x.DateAndTime.ToShortDateString().Equals(dateTime.ToShortDateString())).ToList();
                }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...