Kevin
Kevin

Reputation: 4848

Comparing DateTime fields with different 'times'

My program asks for the user to enter a date which is then converted to a datetime:

var fromDate = DateTime.Parse(txtFromDate.Text);

The reason I'm converting it to a DateTime field is because I want to compare it against DateTime fields in a table, like so:

var q = gc.GraphicRequests.Where(a => a.DateInWork == fromDate);

However, there's a problem. When the user inputs a date (6/17/2013) and it's converted to a DateTime field, the result date looks like this: 6/17/2013 12:00:00 AM.

The problem is, when I'm trying to find records in the table that match that date, I'm not getting any hits because the dates in the table look like this: 6/17/2013 05:35 AM or some other time. So, the date is correct, but the time doesn't match.

My question is, how can I just compare the dates and leave out the time? I just want every record that matches that date, regardless of what time is on the DateTime field.

Upvotes: 1

Views: 198

Answers (3)

Servy
Servy

Reputation: 203829

If your query provider is able to translate it, this would be the option that semantically represents what you want to do:

var q = gc.GraphicRequests.Where(a => a.DateInWork.HasValue 
    && a.DateInWork.Value.Date  == fromDate);

If it doesn't, just see if the date is between the start and end of the day:

DateTime someDate;
DateTime fromDate = someDate.Date, toDate = someDate.Date.AddDays(1);

var q = gc.GraphicRequests.Where(a => a.DateInWork >= fromDate 
    && a.DateInWork < toDate);

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

If you are using entity framework, then use EntityFunctions.TruncateTime method:

var q = gc.GraphicRequests
          .Where(a => EntityFunctions.TruncateTime(a.DateInWork) == fromDate);

If you are using Linq to SQL, then you can simply asses DateTime.Date property. Or even do things like a.DateInWork.Date.Year > 2000.

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149020

You could try using the Date property, which represents the current DateTime without any Time part:

var q = gc.GraphicRequests.Where(a => a.DateInWork.Date == fromDate);

If DateInWork is nullable (i.e. DateTime?), use this:

var q = gc.GraphicRequests.Where(a => 
    a.DateInWork.HasValue && a.DateInWork.Value.Date == fromDate);

However, if you are using Entity Framework, you may need to look at the TruncateTime method:

var q = gc.GraphicRequests.Where(a =>
    EntityFunctions.TruncateTime(a.DateInWork).Value == fromDate);

Upvotes: 4

Related Questions