Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all records within the last Two Days from the current Date using EF 4?

EF 4 in C#.

I have my query, at the moment I'm able to filter the result by the current Date (just date not considering TIME).

I need to filter the result FROM the last two days TO the current Date (no idea how to do it).

I tried in my query currenteDate - 2 but without success.

Could you please give me an example? Thanks for your time on this.

DateTime currenteDate = DateTime.UtcNow.Date;

                var contents = from cnt in context.CmsContents
                               where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date == currenteDate
                               orderby cnt.ContentId descending
                               select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent };
like image 244
GibboK Avatar asked Sep 21 '11 10:09

GibboK


1 Answers

For changing current date you need use currenteDate.AddDays(-2). And use >= instead of == to get all records from 2 days before and till the last record

DateTime currenteDate = DateTime.UtcNow.Date.AddDays(-2);

var contents = from cnt in context.CmsContents
                   where cnt.IsPublished == true & cnt.IsDeleted == false & cnt.Date >= currenteDate
                   orderby cnt.ContentId descending
                   select new { cnt.ContentId, cnt.Title, cnt.TitleUrl, cnt.Date, cnt.TypeContent };
like image 102
Samich Avatar answered Oct 19 '22 08:10

Samich