Linq to SQL DateTime2 查询

发布于 2024-11-06 06:25:56 字数 1086 浏览 0 评论 0原文

我有一个带有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏末 2024-11-13 06:25:56

听起来数据库中的日期实际上不是今天(5 月 8 日)。时间大概是8月5日。

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

终难遇 2024-11-13 06:25:56

看起来您的 datetime2 字段称为“日期”。您需要使用此日期字段的日期属性来忽略一天中的时间。

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文