shanish
shanish

Reputation: 1984

Date comparision using Linq

I have a DateTime type column named "CreatedDate" in my sql table, and am passing the value for this column by using "DateTime.Now" from my asp.net application....

The datas in my CreatedDate column are,

 CreatedDate
 -----------
 2012-05-07 18:56:17.487
 2012-05-07 18:56:28.443
 2012-05-07 19:21:24.497
 2012-05-14 15:22:04.587

I need to get the datas with this CreatedDate.

in my entity framework I tried the condition like

DataAccess.Entities dataEntities = new DataAccess.Entities();

DataAccess.Employee employee = dataEntities.Employees
                              .First(e => e.CreatedDate == DateTime.Today);

like this, I have data for this date(2012-05-14) , but the mininutes part differes (the DateTime.Today gives '2012-05-14 12:00:000' like this) here, and it shows error like, sequence contains no element....

How can I compare the 'Date' alone in Linq.....can anyone help me here,,,

Upvotes: 1

Views: 219

Answers (3)

shanish
shanish

Reputation: 1984

I just declared two variable like

DateTime date1=DateTime.Now.Date;
DateTime date2=DateTime.Now.Date.AddDays(1);

and in the condition I used these variables like

DataAccess.Employee employee = dataEntities.Employees
                          .First(e => e.CreatedDate >= date1 
                                   && e.CreatedDate < date2);

its working....

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Try this:

DataAccess.Employee employee =
    dataEntities.Employees.First(e=>e.CreatedDate.Date==DateTime.Today)

Upvotes: 1

Shyju
Shyju

Reputation: 218722

Use the Date Property on the DateTime object

CreatedDate.Date==DateTime.Today

So your code will be

DataAccess.Employee employee=dataEntities.
                     Employees.First(e=>e.CreatedDate.Date==DateTime.Today);

Date Property returns the Date Component of the DateTime object and the time value set to 12:00:00 midnight (00:00:00).

Upvotes: 2

Related Questions