Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq if DateTime field is older than X hours

I have tried the following (obviously without the //), but I can't get any to work, can anybody help please?

    public void CleanBasket()
    {
        //double validHours = 3;
        // var expired = (from a in db.Baskets where (DateTime.Now - a.DateCreated).TotalHours > validHours  select a);
        //var expired = (from a in db.Baskets where (DateTime.Now.Subtract(a.DateCreated).Hours > 3) select a);
        //var expired = (from a in db.Baskets where(a => a.DateCreated > DateTime.Now.AddHours(-1));
        //foreach (Basket basket in expired) db.DeleteObject(expired);
        db.SaveChanges();
    }
like image 710
Gravy Avatar asked Apr 23 '12 23:04

Gravy


1 Answers

In this case surely you can simply do your date time calculation before you invoke LINQ:

double validHours = 3;
var latest = DateTime.UtcNow.AddHours(-validHours);
var expired = (from a in db.Baskets where a.DateCreated < latest select a);

For any more complex DateTime operations that you need to do in the database and cannot do this way you can use SqlFunctions.

BTW you should store your times in Utc not local time. Calculations using DateTime.Now will be wrong during daylight savings time changes.

like image 111
Ian Mercer Avatar answered Sep 19 '22 11:09

Ian Mercer