Home Compare dates linq c#
Reply: 3

Compare dates linq c#

JohnDoe
1#
JohnDoe Published in 2017-11-13 20:14:50Z

This question already has an answer here:

  • How to compare only date components from DateTime in EF? 15 answers

I cant seem to get my query to check the database if a date exists. Please help.

 DateTime value = new DateTime(2018, 10, 26);
 item = await table.Where(todoItem => todoItem.Date == value.date)
                   .ToListAsync();

I think the format which c# writes their dates and SQL are different so it cant find a match. Also the database is correctly linked to the app as I am able to query other rows in the same table.

Erik Philips
2#
Erik Philips Reply to 2017-11-13 20:23:40Z

This is most likely caused by including a time in your dates, and not formatting them to just the actual date string. You can resolve this by using the .toLocaleString() method. Something like this should work:

DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => todoItem.Date.toLocaleString() == 
  value.date.toLocaleString())
  .ToListAsync();
Igor
3#
Igor Reply to 2017-11-13 20:36:00Z

As said before, this is likely due to the fact that your DateTime column in the database includes time information.

Rewrite your query like this:

DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => todoItem.Date >= value &&
                                     todoItem.Date < value.AddDays(1))
                   .ToListAsync();

This will retrieve all records that fall within the specified range (that is, dates that match the given day, and the DBMS will be able to use indexes that might be defined on the date-column.

GTown-Coder
4#
GTown-Coder Reply to 2017-11-13 20:28:30Z

Similar to Brandon's answer.. this is most likely happening due to todoItem.Date including the time portion of the Date property.

I assume the property Date is of type DateTime, so you could do this:

DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => DbFunctions.TruncateTime(todoItem.Date) == 
  value).ToListAsync();

DbFunctions.TruncateTime

When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.

Here is more information on DbFunctions.TruncateTime.

Let me know if this helps!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.320226 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO