How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?
Solution 1:
try using the Date
property on the DateTime
Object...
if(dtOne.Date == dtTwo.Date)
....
Solution 2:
For a true comparison, you can use:
dateTime1.Date.CompareTo(dateTime2.Date);
Solution 3:
This is how I do this in order to work with LINQ.
DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));
If you only use dtOne.Date == dtTwo.Date
it wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)
Solution 4:
If you're using Entity Framework < v6.0, then use EntityFunctions.TruncateTime
If you're using Entity Framework >= v6.0, then use DbFunctions.TruncateTime
Use either (based on your EF version) around any DateTime
class property you want to use inside your Linq query
Example
var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate)
>= DbFunctions.TruncateTime(DateTime.UtcNow));
Solution 5:
DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
MessageBox.Show("Valid Date");
}
else
{
MessageBox.Show("Invalid Date... Please Give Correct Date....");
}