如何比较EF中DateTime的日期组件? [英] How to compare only date components from DateTime in EF?

查看:685
本文介绍了如何比较EF中DateTime的日期组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期值,一个已经存储在数据库中,另一个由用户使用DatePicker选择。用例是从数据库中搜索特定日期。



以前在数据库中输入的值始终具有12:00:00的时间分量,其中从选择器输入的日期具有不同的时间分量。



我只对日期组件感兴趣,并希望忽略时间组件。



在C#中执行此比较的方法有哪些?



另外,如何在LINQ中执行此操作?



更新:
在LINQ to Entities上,以下工作正常。

 code> e => DateTime.Compare(e.FirstDate.Value,SecondDate)> = 0 


解决方案

注意:在撰写此回答时,EF关系不清楚(在写入问题后被编辑)。对于使用EF的正确方法,请查看 Mandeeps答案






您可以使用 DateTime.Date 属性执行日期比较。

  DateTime a = GetFirstDate(); 
DateTime b = GetSecondDate();

if(a.Date.Equals(b.Date))
{
//日期相等
}


I am having two date values, one already stored in the database and the other selected by the user using DatePicker. The use case is to search for a particular date from the database.

The value previously entered in the database always has time component of 12:00:00, where as the date entered from picker has different time component.

I am interested in only the date components and would like to ignore the time component.

What are the ways to do this comparison in C#?

Also, how to do this in LINQ?

UPDATE: On LINQ to Entities, the following works fine.

e => DateTime.Compare(e.FirstDate.Value, SecondDate) >= 0

解决方案

NOTE: at the time of writing this answer, the EF-relation was unclear (that was edited into the question after this was written). For correct approach with EF, check Mandeeps answer.


You can use the DateTime.Date property to perform a date-only comparison.

DateTime a = GetFirstDate();
DateTime b = GetSecondDate();

if (a.Date.Equals(b.Date))
{
    // the dates are equal
}

这篇关于如何比较EF中DateTime的日期组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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