如何通过LINQ比较的DateTime没有时间? [英] How to compare DateTime without time via LINQ?

查看:213
本文介绍了如何通过LINQ比较的DateTime没有时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var q = db.Games.Where(t => t.StartDate >= DateTime.Now).OrderBy(d => d.StartDate);

但它比较包括的DateTime 时间的一部分。我真的不需要它。

But it compares including time part of DateTime. I really don't need it.

如何做没有时间?

感谢您!

推荐答案

只需使用日期属性:

var today = DateTime.Today;

var q = db.Games.Where(t => t.StartDate.Date >= today)
                .OrderBy(t => t.StartDate);

请注意,我已经明确地评估 DateTime.Today 一次的,这样的查询是一致的 - 否则,在执行查询每一次,和即使的的执行,今天可能会改变,所以你会得到不一致的结果。例如,假设你有数据:

Note that I've explicitly evaluated DateTime.Today once so that the query is consistent - otherwise each time the query is executed, and even within the execution, Today could change, so you'd get inconsistent results. For example, suppose you had data of:

Entry 1: March 8th, 8am
Entry 2: March 10th, 10pm
Entry 3: March 8th, 5am
Entry 4: March 9th, 8pm

当然,任何的两个的条目1和3应该是结果,或则他们两者均应...但如果​​你评估的DateTime 的。今天和它的修改的到3月9日之后,它执行的第一个两次检查,你可能最终与项1,2,4。

Surely either both entries 1 and 3 should be in the results, or neither of them should... but if you evaluate DateTime.Today and it changes to March 9th after it's performed the first two checks, you could end up with entries 1, 2, 4.

当然,使用 DateTime.Today 假设你有兴趣在本地的时区的日期。这可能并不合适,你应该做的绝对的确保你知道你的意思。您的可以的要使用 DateTime.UtcNow.Date 来代替,例如。不幸的是,<一个href="http://noda-time.blogspot.com/2011/08/what-wrong-with-datetime-anyway.html"><$c$c>DateTime是一个光滑的野兽 ...

Of course, using DateTime.Today assumes you're interested in the date in the local time zone. That may not be appropriate, and you should make absolutely sure you know what you mean. You may want to use DateTime.UtcNow.Date instead, for example. Unfortunately, DateTime is a slippery beast...

编辑:您可能还希望得到完全摆脱调用到的DateTime 静态属性 - 它们使code很难进行单元测试。在野田佳彦时间我们有这个目的的界面,专(<一href="http://noda-time.google$c$c.com/hg/docs/api/html/T_NodaTime_IClock.htm"><$c$c>IClock)这是我们期待的要进行适当的注入。有一个系统时间的实施进行生产和一个存根的实施进行测试,或者您也可以自己实现它。

You may also want to get rid of the calls to DateTime static properties altogether - they make the code hard to unit test. In Noda Time we have an interface specifically for this purpose (IClock) which we'd expect to be injected appropriately. There's a "system time" implementation for production and a "stub" implementation for testing, or you can implement it yourself.

您可以使用同样的想法,而不使用过程中的野田时间。单元测试这个特别的code,你可能想传递的日期,但你会从的地方得到它的 - 和注射时钟意味着你可以测试的所有的code。

You can use the same idea without using Noda Time, of course. To unit test this particular piece of code you may want to pass the date in, but you'll be getting it from somewhere - and injecting a clock means you can test all the code.

这篇关于如何通过LINQ比较的DateTime没有时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆