I have a database table with columns of type dateTime
.
Now I need to see if there already is a row with today’s date, but I don’t know how to compare the column with the current date without the hour, minutes, seconds.
Basically I have 2022-02-04 14:06:21.080
and I need to check if there is a row created on 2022-02-04
.
I’m looking for something like
if (db.dates.Where(x => x.SentDate == Date.Now).Count() > 0)
{
// Do something
}
else
{
// Do something else
}
I only need to see if it has a date from today it doesn’t matter what time it was created.
Any help is much appreciated!
5
Answers
You can check a date range
The DateTime.Today Property gets the current date with the time component set to 00:00:00.
Note that we test the lower bound with
>= today
(withtoday
meaning today at 00:00:00) but the upper one with< tomorrow
, since we do not want to include tomorrow at 00:00:00.If you’re filtering for a specific date you can use the
DateTime.Date
property on bothDateTime
objects. This will compare the date component of theDateTime
:If you have a nullable
DateTime?
column, then you use theValue
property along withHasValue
:Unfortunately, expression trees do not support the null propagation operator
?.
so we need to use the above method instead.DateTime.Date
can also be used for date ranges, but take care with the upper bound.PS:
DateTime.Today
is the same asDateTime.Now.Date
If you use MS SQL Server you can use a special function
EF.Functions.DateDiff
that was created to be used with EF. It can count datetime difference from seconds to months.DateDiffDay
is used to count days.Another way is to convert the dates to string and compare.
You can check a date range
The DateTime.Today Property gets the current date with the time component set to 00:00:00.