Coder Perfect

In Linq to SQL with Entity Framework, how do you compare solely Date without Time in DateTime types?


Is there a method to compare two DateTime variables in Linq2Sql without taking into account the Time component?

The program saves items in the database and adds a date to them. I’d like to maintain the exact time while yet being able to use the date.

I’d like to compare 12/3/89 12:43:34 with 12/3/89 11:22:12, ignoring the time of day, so that both of these are treated the same.

I suppose I could set all the hours to 00:00:00 before comparing, but I don’t really care about the time of day; I simply want to be able to compare by date alone.

I came across some code that suffers from the same problem, and it compares the year, month, and day separately. Is there a more efficient method to accomplish this?

Asked by Sruly

Solution #1

try using the Date property on the DateTime Object…

if(dtOne.Date == dtTwo.Date)

Answered by Quintin Robinson

Solution #2

You can use the following to make a true comparison:


Answered by Reed Copsey

Solution #3

This is how I do it while working with LINQ.

DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
                EntityFunctions.TruncateTime( == EntityFunctions.TruncateTime(date_to_compare));

If you only use dtOne. Date == dtTwo. Date it wont work with LINQ (Error: The specified type member ‘Date’ is not supported in LINQ to Entities)

Answered by Alejandro del Río

Solution #4

Use EntityFunctions if you’re using Entity Framework v6.0. TruncateTime Use DbFunctions if you’re using Entity Framework >= v6.0. TruncateTim

Around every DateTime class property you want to use inside your Linq query, use either (depending on your EF version).


var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate) 
                                       >= DbFunctions.TruncateTime(DateTime.UtcNow));

Answered by Korayem

Solution #5

DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
    MessageBox.Show("Valid Date");
    MessageBox.Show("Invalid Date... Please Give Correct Date....");

Answered by Devarajan.T

Post is based on