DbFunctions or similar to compare time of day of a datetime type column in Linq to Entity Framework

393 Views Asked by At

I know there is a function to compare just the date of a datetime type column, but what if I want to only compare the time of it to another time. Is there a function in Linq To Entities?

DbFunctions.TruncateTime(q.EndDate.Value)
2

There are 2 best solutions below

0
Mike Flynn On BEST ANSWER

I used this and it worked fine.

SqlFunctions.DatePart("hh", t.Time.Value) == SqlFunctions.DatePart("hh", newTime) && SqlFunctions.DatePart("n", t.Time.Value) == SqlFunctions.DatePart("n", newTime) 
0
Steve Py On

It's not pretty, but you can use a combination of a Diff variant method with TruncateTime. For example, to compare a time down to the second:

DbFunctions.DiffSeconds(DbFunctions.TrucateTime(x.Date1), x.Date1) -
    DbFunctions.DiffSeconds(DbFunctions.TrucateTime(x.Date2), x.Date2) == 0

Would tell you if the two times (on different dates) are the same or not.