Search code examples
c#linqdatetimemilliseconds

LINQ DateTime Query that ignores milliseconds


x.CreateDate DateTime is stored in our database down to milliseconds. My dateTimePicker values startdate and enddate only allows for querying down to seconds.

How can change my query to ignore the milliseconds of x.CreateDate? I thought the code I wrote below would work but it is not.

if (stardDateIsValid && endDateIsValid && startdate == enddate)
    query = _context.Logs
        .Where(x => x.ApplicationID == applicationId &&
                    x.CreateDate.AddMilliseconds(-x.CreateDate.Millisecond) == startdate)
        .OrderByDescending(x => x.ID)
        .Take(count);

Solution

  • I have no idea why I could not get any results from the queries posted above as I tried several variations of their themes. However I did get it working correctly by adding milliseconds to the startdate and enddate variables and it s working.

    if (stardDateIsValid && endDateIsValid)
       startdate = startdate.AddMilliseconds(000);
       enddate = enddate.AddMilliseconds(999);
       query = _context.Logs.Where(x => x.ApplicationID == applicationId && x.CreateDate >= startdate && x.CreateDate <= enddate).OrderByDescending(x => x.ID).Take(count);