简体   繁体   中英

How to compare date value only in LINQ

I am trying to get the records from database where StartTime field should be today's date.

service.GetAll().Where(o => o.StartTime. == DateTime.Today.Date).Select(o => new SelectableItem(o.Id, o.TestPurpose, v == o.Id))

The date in database is of this format.

2016-07-01 07:00:00.000

How do I compare this format with today's date, I need to compare only date and not the time.

You can use approach specified by @Renan Araujo. Or another way is, define two dates and use

.Where(o => o.StartTime >= date1 && o.StartTime < date2)

where

  date1 = DateTime.Today.Date;            // (lets say today's date=10-13-2016 )
  date2 = DateTime.Today.AddDays(1).Date; // (tomorrow's date = 10-14-2016)

Use EntityFunctions.TruncateTime to remove the time portion:

service.GetAll()
.Where(o => EntityFunctions.TruncateTime(o.StartTime) == EntityFunctions.TruncateTime(DateTime.Today.Date))
.Select(o => new SelectableItem(o.Id, o.TestPurpose, v == o.Id))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM