0

I have a table with a datetime2 field and I need to get all rows out of it where the date is today. Rather oddly (in my opinion but I'm sure there's a valid reason for it) if I do:

MyTable.Where(t => t.Date == DateTime.Today).ToList()

it returns nothing even though there are entires with todays date.

What am I missing here? I thought that datetime2 allowed you to query like this instead of having to use greater than and less than to specify a timeframe?

Edit

I've tried using the .Date portion of the DateTime2 representation in Linq to SQL:

MyTable.Where(t => t.Date.Date == DateTime.Today).ToList()

but I'm still getting nothing. Yet in my database there are rows with the value 2011-08-05 00:00:00.0000000 which is clearly today.

Edit again I've ran the query:

List<string> dates = MyTable.Select(t => t.Date.Date.ToString()).ToList();

and I'm getting results like 2011-08-05, so that portion obviously works.

However, when I run

DateTime.Today.Date.ToString()

I get 08/05/2011 00:00:00. Could the addition of this time portion be causing the issue? How would I remove this?

Edit 3

Got it to work using the code:

MyTable.Where(t => t.Date.Date.ToString() == DateTime.Today.Date.ToString("yyyy-dd-MM")).ToList();

This seems hacky though (converting to a string before comparison) and surely there must be a cleaner way?

4
  • Is there a time stored with the date? Commented May 8, 2011 at 14:57
  • @Conrad yea there's a time stored too, but I just want everything today. Commented May 8, 2011 at 15:01
  • You need to get a look at the raw sql that L2S is generating. Commented May 8, 2011 at 15:18
  • Do you have the code that is actually inserting the DateTime into the datebase. Can you confirm that the date in the db is definitely 8th May rather than 5th August? Commented May 8, 2011 at 18:40

2 Answers 2

1

It sounds like the date in the database isn't actually today (8th May). It's probably 5th August.

Sign up to request clarification or add additional context in comments.

3 Comments

that's what I'm thinking. how can i change that?
We need to see the code that is inserting the date time. Or did you just use Management Studio to get some test data in there...?
Ha - easy mistake to make...at least it's fixed now.
0

It looks like your datetime2 field is called Date. You need to use the Date property of this Date field to ignore the time of day.

MyTable.Where(t => t.Date.Date == DateTime.Today).ToList()

4 Comments

would it not need to be: MyTable.Where(t => t.Date.Date == DateTime.Today.Date).ToList()
@Lee: DateTime.Today is the same as DateTime.Now.Date, you don't need to .Date since Today doesn't include the time.
I've edited the question a few times there guys with more info.
@vcsjones ah yeah - in my head I must of saw DateTime.Now - thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.