Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates in LINQ?

Tags:

.net

linq

I want to check if a given date is more than a month earlier than today's date using LINQ.

What is the syntax for this?

Thanks in advance.

like image 873
TedH Avatar asked Oct 18 '08 02:10

TedH


People also ask

How do I compare two dates in LINQ query with time?

Meeting dates are stored in this table using the following format: May 2nd 2011 is (for example) formatted as 5/2/2011 . My requirement is to get the meetings between two dates (say, 4/25/2011 and 5/2/2011) and to write a query comparing a date with these two dates. Does it compare like 4/25/2011 < 4/26/2011?


3 Answers

I assume that you're talking about in the where clause. It's basically the same way you would compare two DateTime objects elsewhere.

using (DataContext context = new DataContext()) {
   var query = from t in context.table
               where t.CreateDate.Date < DateTime.Today.AddMonths(-1)
               select t;
}
like image 84
tvanfosson Avatar answered Oct 11 '22 06:10

tvanfosson


Just to add, in LINQ To Entities you have to compare to a variable. Example:

        DateTime lastMonth = DateTime.Today.AddMonths(-1);
        using (var db = new MyEntities())
        {
            var query = from s in db.ViewOrTable
                        orderby s.ColName
                        where (s.StartDate > lastMonth)
                        select s;

            _dsResults = query.ToList();
        }
like image 29
live-love Avatar answered Oct 11 '22 07:10

live-love


If you don't want your code to throw

LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression.

I would suggest using DbFunctions.AddYears. Also, if you are concerned only about dates and not the times, you could use DbFunctions.TruncateTime

Something like this-

DbFunctions.TruncateTime(x.date) ==
DbFunctions.TruncateTime(DbFunctions.AddYears(DateTime.Today, 1))
like image 41
Pallavi Avatar answered Oct 11 '22 07:10

Pallavi