Linq where clause compare only date value without time value
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.
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.
There is also EntityFunctions.TruncateTime
or DbFunctions.TruncateTime
in EF 6.0
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.
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.
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.
EDIT
If you just want to compare the date value of the date time than make use of
DateTime.Date
Property - Gets the date component of this instance.
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.
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";