C# Linq where 子句只比较日期值而不比较时间值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13510849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:49:41  来源:igfitidea点击:

Linq where clause compare only date value without time value

c#entity-frameworkdatetimelinq-to-entitiescompare

提问by Frank Myat Thu

var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
        && x.DateTimeValueColumn <= DateTime.Now)
    .Select(x => x);

Upper query is working correct.
But I want to check only date value only.
But upper query check date + time value.

上层查询工作正常。
但我只想检查日期值。
但上查询检查日期+时间值。

In traditional mssql, I could write query like below.

在传统的 mssql 中,我可以编写如下查询。

SELECT * FROM dbo.tbl_MyTable
WHERE 
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) <= 
            CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
AND
Active = 1

So could anyone give me suggestion how could I check only date value in Linq.

那么任何人都可以给我建议如何只检查 Linq 中的日期值。

采纳答案by Johann Blais

There is also EntityFunctions.TruncateTimeor DbFunctions.TruncateTimein EF 6.0

还有EntityFunctions.TruncateTimeDbFunctions.TruncateTime在 EF 6.0

回答by Pranay Rana

EDIT

编辑

To avoid this error : The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

为避免此错误:LINQ to Entities 中不支持指定的类型成员“Date”。仅支持初始值设定项、实体成员和实体导航属性。

var _My_ResetSet_Array = _DB
                .tbl_MyTable
                .Where(x => x.Active == true)
                         .Select(x => x).ToList();

 var filterdata = _My_ResetSet_Array
        .Where(x=>DateTime.Compare(x.DateTimeValueColumn.Date, DateTime.Now.Date)  <= 0 );

The second line is required because LINQ to Entity is not able to convert date property to sql query. So its better to first fetch the data and then apply the date filter.

第二行是必需的,因为 LINQ to Entity 无法将日期属性转换为 sql 查询。所以最好先获取数据,然后应用日期过滤器。

EDIT

编辑

If you just want to compare the date value of the date time than make use of

如果您只想比较日期时间的日期值而不是使用

DateTime.DateProperty- Gets the date component of this instance.

DateTime.Date属性- 获取此实例的日期组件。

Code for you

给你的代码

var _My_ResetSet_Array = _DB
                .tbl_MyTable
                .Where(x => x.Active == true
     && DateTime.Compare(x.DateTimeValueColumn.Date, DateTime.Now.Date)  <= 0 )
                         .Select(x => x);


If its like that then use

如果它像那样然后使用

DateTime.Compare Method- Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

DateTime.Compare 方法- 比较DateTime 的两个实例并返回一个整数,指示第一个实例是早于、相同还是晚于第二个实例。

Code for you

给你的代码

var _My_ResetSet_Array = _DB
                .tbl_MyTable
                .Where(x => x.Active == true
                  && DateTime.Compare(x.DateTimeValueColumn, DateTime.Now)  <= 0 )
                         .Select(x => x);

Example

例子

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

回答by igrimpe

Use mydate.Dateto work with the date part of the DateTime class only.

mydate.Date用于处理 DateTime 类的日期部分。

回答by Pranay Rana

Simple workaround to this problem to compare date part only

此问题的简单解决方法是仅比较日期部分

var _My_ResetSet_Array = _DB
                    .tbl_MyTable
                    .Where(x => x.Active == true && 
                               x.DateTimeValueColumn.Year == DateTime.Now.Year
                            && x.DateTimeValueColumn.Month == DateTime.Now.Month
                            && x.DateTimeValueColumn.Day == DateTime.Now.Day);

Because 'Date' datatype is not supported by linq to entity , where as Year, Month and Day are 'int' datatypes and are supported.

因为 linq to entity 不支持 'Date' 数据类型,而 Year、Month 和 Day 是 'int' 数据类型并且受支持。

回答by Joe Stellato

&& x.DateTimeValueColumn <= DateTime.Now

&& x.DateTimeValueColumn <= DateTime.Now

This is supported so long as your schema is correct

只要您的架构正确,就支持此操作

&& x.DateTimeValueColumn.Value.Date <=DateTime.Now

回答by takemyoxygen

In similar case I used the following code:

在类似的情况下,我使用了以下代码:

DateTime upperBound = DateTime.Today.AddDays(1); // If today is October 9, then upperBound is set to 2012-10-10 00:00:00
return var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
        && x.DateTimeValueColumn < upperBound) // Accepts all dates earlier than October 10, time of day doesn't matter here
    .Select(x => x);

回答by Jatin

 result = from r in result where (r.Reserchflag == true && 
    (r.ResearchDate.Value.Date >= FromDate.Date && 
     r.ResearchDate.Value.Date <= ToDate.Date)) select r;

回答by Soharab Shaikh

Working code :

工作代码:

     {
        DataBaseEntity db = new DataBaseEntity (); //This is EF entity
        string dateCheck="5/21/2018";
        var list= db.tbl
        .where(x=>(x.DOE.Value.Month
              +"/"+x.DOE.Value.Day
              +"/"+x.DOE.Value.Year)
             .ToString()
             .Contains(dateCheck))
     }

回答by Karthic G

Try this,

尝试这个,

var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
         && x.DateTimeValueColumn <= DateTime.Now)
    .Select(x => x.DateTimeValueColumn)
    .AsEnumerable()
    .select(p=>p.DateTimeValueColumn.value.toString("YYYY-MMM-dd");

回答by Roberto Mutti

Do not simplify the code to avoid "linq translation error": The test consist between a date with time at 0:0:0 and the same date with time at 23:59:59

不要简化代码以避免“linq 翻译错误”:测试包括时间为 0:0:0 的日期和时间为 23:59:59 的同一日期

        iFilter.MyDate1 = DateTime.Today;  // or DateTime.MinValue

        // GET 
        var tempQuery = ctx.MyTable.AsQueryable();

        if (iFilter.MyDate1 != DateTime.MinValue)
        {
            TimeSpan temp24h = new TimeSpan(23,59,59);
            DateTime tempEndMyDate1 = iFilter.MyDate1.Add(temp24h);

            // DO not change the code below, you need 2 date variables...
            tempQuery = tempQuery.Where(w => w.MyDate2 >= iFilter.MyDate1
                                          && w.MyDate2 <= tempEndMyDate1);
        }

        List<MyTable> returnObject = tempQuery.ToList();