views:

6283

answers:

3

Is there a way to compare 2 DateTime variables in Linq2Sql but to disregard the Time part.

The app stores items in the DB and adds a published date. I want to keep the exact time but still be able to pull by the date itself.

I want to compare 12/3/89 12:43:34 and 12/3/89 11:22:12 and have it disregard the actual time of day so both of these are considered the same.

I guess I can set all the times of day to 00:00:00 before I compare but I actually do want to know the time of day I just also want to be able to compare by date only.

I found some code that has the same issue and they compare the year, month and day separately. Is there a better way to do this?

+19  A: 

try using the Date property on the DateTime Object...

if(dtOne.Date == dtTwo.Date)
    ....
Quintin Robinson
+1  A: 

For a true comparison, you can use:

dateTime1.Date.CompareTo(dateTime2.Date);
Reed Copsey
doesn't "==" return the results from CompareTo internally?
SnOrfus
What exactly do you mean by "true comparison"?
Randolpho
SnOrfus: Not always. Many implementations return a.CompareTo(b)==0 for ==, but that's up to the implementation. I haven't checked DateTime's internal implemetnation of equality.
Reed Copsey
Randolpho: Using == will give you equality, so whether the two dates are the same or different. CompareTo will ~compare~ them, ie: give you a way in one pass to tell if date1>date2, date1<date2, or date1==date2.
Reed Copsey
A: 

In your join or where clause, use the Date property of the column. Behind the scenes, this executes a CONVERT(DATE, <expression>) operation. This should allow you to compare dates without the time.

Adam Robinson