Linq比较2个日期

时间:2014-01-30 00:16:44

标签: c# linq entity-framework-4

我想比较日期。表中的值是DateTime with format 2014-01-29 09:00:00.000请指教,谢谢

public static List<vwReportDate> GetDetail(string startDate, string endDate)
{
    startDate = "2014-01-28";
    endDate = "2014-01-28";

    DateTime dtStart = Convert.ToDateTime(startDate);
    DateTime dtEndDate = Convert.ToDateTime(endDate);


    var entities = new DataEntiies();
    var query = from c in entities.vwReportDate
                where c.EventCreateDate >= dtStart && c.EventCreateDate <= dtEndDate
                select c;
    return query.ToList();

}

3 个答案:

答案 0 :(得分:3)

看起来您正在使用Entity Framework和LINQ to EF。如果这是真的,你不能在LINQ to EF中使用DateTime.Date属性because it's not supported。您必须使用EntityFunctions.TruncateTime(myDateTime)静态方法:

var query = from c in entities.vwReportDate
            let eventDate = EntityFunctions.TruncateTime(c.EventCreateDate)
            where eventDate >= dtStart && eventDate <= dtEndDate
            select c;

答案 1 :(得分:2)

我对此问题的解决方法(不依赖于EF)是在日期范围的末尾使用“小于”(在向前移动日期范围的一天之后):

startDate = "2014-01-28";
endDate = "2014-01-28";

DateTime dtStart = Convert.ToDateTime(startDate);
DateTime dtEndDate = Convert.ToDateTime(endDate).AddDays(1);


var entities = new DataEntiies();
var query = from c in entities.vwReportDate
            where c.EventCreateDate >= dtStart && c.EventCreateDate < dtEndDate
            select c;
return query.ToList();

问题:为什么要忽略方法调用者提供的参数值?

答案 2 :(得分:1)

使用DateTime结构的Date属性来检索“日期”部分。

  

获取此实例的日期组件。

在代码中使用它:

var query = from c in entities.vwReportDate
            where c.EventCreateDate.Date >= dtStart && c.EventCreateDate.Date <= dtEndDate
            select c;

如果你正在使用Entity框架(就像你看到的那样),你将不得不使用EntityFunctions.TruncateTime(帮助器)方法,否则无法转换查询。

var query = from c in entities.vwReportDate
            where EntityFunctions.TruncateTime(c.EventCreateDate) >= dtStart && EntityFunctions.TruncateTime(c.EventCreateDate) <= dtEndDate
            select c;