8

I'm trying to run the following bit of code, but the comparison fails by not handing my the entities I expect it to.

It's comparing 06/09/2011 0:00:00 to 06/09/2011 12:25:00, the latter being my databases record value. So that's why the comparison is failing and I'm not getting the records I need.

I'm just trying to compare if the dates match up, I'm don't care about the time.

DateTime today = DateTime.Now.Date;
var newAuctionsResults = repo.FindAllAuctions()
                        .Where(a => a.IsActive == true || a.StartTime.Value == today)
                        .ToList();

How can I compare only the dates?

If use the .Date property in the .StartTime.Value part, I get an exception:

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257
  • Maybe this question will help? LINQ | How do I perform Date Comparison in a Linq Query? http://stackoverflow.com/questions/1088212/linq-how-do-i-perform-date-comparison-in-a-linq-query – Kyle Sep 06 '11 at 13:31

4 Answers4

16

You can use the individual members:

var newAuctionsResults = repo.FindAllAuctions()
                        .Where(a => a.IsActive == true 
                                    || (a.StartTime.Value.Year == todayYear
                                        && a.StartTime.Value.Month == todayMonth
                                        && a.StartTime.Value.Day == todayDay))
                        .ToList();

...or use any of the other methods/properties supported in L2E.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
11

You can also use EntityFunctions.TruncateTime() under the namespace System.Data.Objects

Ex.

db.Orders.Where(i => EntityFunctions.TruncateTime(i.OrderFinishDate) == EntityFunctions.TruncateTime(dtBillDate) && i.Status == "B")

Works like charm.

صفي
  • 1,068
  • 2
  • 15
  • 34
-1

try

DateTime todayStart = DateTime.Now.Date;
DateTime todayEnd = DateTime.Now;
var newAuctionsResults = repo.FindAllAuctions()
                        .Where(a => a.IsActive == true || (a.StartTime.Value >= todayStart && a.StartTime.Value <= todayEnd))
                        .ToList();
Yahia
  • 69,653
  • 9
  • 115
  • 144
-2

You could convert using

DateTime.ToShortDateString()

http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx

This would neglect the Time.

Then compare the two Strings.

if(string1 == string2)
{
 //Do Something
}
Mac
  • 382
  • 2
  • 8
  • 26