Search code examples
c#linqdatetimedbfunctions

DbFunctions DiffDays Gives wrong answer


I want to get a list from DataBase, where MyDate is today or tomarrow.
I wrote the following code.

_Log("Now: " + DateTime.Now.ToString());

var v = db_TS.TS_Test.Where(x => DbFunctions.DiffDays(x.MyDate,DateTime.Now) < 2);
foreach (var item in v.ToList())
{
     _Log("MyDate: " + item.MyDate.ToString());
}

The following is logged:

Now: 11/08/2016 10:50:00
MyDate: 27/09/2017 09:35:00

Please help me to find what went wrong in the code?
Thank you


Solution

  • You should be doing DbFunctions.DiffDays(DateTime.Now,x.MyDate) since it's supposed to work like subtracting the first parameter from the second one, so in your case, the DiffDays is returning a negative number.

    Summarizing it if you have DbFunctions.DiffDays(date1,date2)

    and date1 > date2 the result will be < 0

    and date1 < date2 the result will be > 0