Entity Framework – Date and Time


Short example of how to compare the date and time with Entity Framework query. Also, how to truncate the time from a Date Time value,

Compare Time

With DateTime.Today() for the date and DateTime.Now() for the time.

var currentDateTime = DateTime.Today;
var currentDateTimeHour = DateTime.Now.Hour;

var qryResults = from a in db.table1.Where(col => col.Category == CategoryId)
                                 .Where(col =>    col.title.Contains(searchString))
join b in db.table2 on a.DynoType equals b.Id
where a.DateTimeColumn >= currentDateTime
where a.DateTimeColumn.Hour >= currentDateTimeHour
select new

To filter by todays date and an hour or X minutes in the future or back in time use the AddHours(), AddMinutes()

var currentDateTimeHour = DateTime.Now.AddHours(-1).Hour; // Past - Hour ago

var currentDateTimeHour = DateTime.Now.AddHours(1).Hour; // Future - Hour from now

To remove the time portion of a Date Time column/variable use DbFunctions.Truncate()

Import the following library

using System.Data.Entity;
  select new
      StartDateTimeTrunc = DbFunctions.TruncateTime(a.StartDate),

Would return the following:

StartDate: "2022-02-03T14:55:00"
StartDateTimeTrunc: "2022-02-03T00:00:00"