Linq to SQL DateTime2 查询
我有一个带有 datetime2 字段的表,我需要从中获取今天日期的所有行。如果我这样做,那就很奇怪(在我看来,但我确信这是有正当理由的):
MyTable.Where(t => t.Date == DateTime.Today).ToList()
即使今天的日期有完整的内容,它也不会返回任何内容。
我在这里缺少什么?我认为 datetime2 允许您像这样查询,而不必使用大于和小于来指定时间范围?
编辑
我尝试在 Linq to SQL 中使用 DateTime2 表示形式的 .Date 部分:
MyTable.Where(t => t.Date.Date == DateTime.Today).ToList()
但我仍然一无所获。然而,在我的数据库中,有一些行的值是 2011-08-05 00:00:00.0000000
,这显然是今天的值。
再次编辑 我已经运行了查询:
List<string> dates = MyTable.Select(t => t.Date.Date.ToString()).ToList();
并且得到了类似 2011-08-05
的结果,因此该部分显然有效。
但是,当我运行时,
DateTime.Today.Date.ToString()
我得到 08/05/2011 00:00:00
。添加这段时间部分是否会导致问题?我该如何删除这个?
编辑3
使用代码让它工作:
MyTable.Where(t => t.Date.Date.ToString() == DateTime.Today.Date.ToString("yyyy-dd-MM")).ToList();
虽然这看起来很老套(在比较之前转换为字符串),但肯定有一个更干净的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来数据库中的日期实际上不是今天(5 月 8 日)。时间大概是8月5日。
It sounds like the date in the database isn't actually today (8th May). It's probably 5th August.
看起来您的 datetime2 字段称为“日期”。您需要使用此日期字段的日期属性来忽略一天中的时间。
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.