How to subtract dates in a linq query

1

I need the subtraction now - a.DateLowStock to be> = 14 days. How can I do it?

        ICollection<Product> products = new List<Product>();
        DateTime now = DateTime.Now();

        using (ApplicationDbContext db = new ApplicationDbContext())
        {
            products = (from a in db.Products
                        where now - a.DateLowStock >= "14 dias").ToList
        }
        return products;
    }

DateLowStock is DateTime? and where it says "14 days" is the condition that I want it to comply with in order to add it to the list. Instead of "14 days", what should I put?

Thanks in advance.

    
asked by Facundo Blanco 07.11.2018 в 19:38
source

2 answers

1

Subtraction of two dates, returns a TimeSpan .

Which is logical, because the subtraction of two dates, is another date, or in this case, a time interval.

This structure has several properties, and among them, the one that interests us in particular is Days . Keep in mind, that this value can be positive or negative.

Therefore, in your linq, we can (and should) do something like this:

((TimeSpan)(now - a.DateLowStock)).Days >= 14

Now, if you ask yourself why all this parenthesis, it is to make the correct conversion when subtracting the data.

    
answered by 07.11.2018 / 19:57
source
2

In linq you have to use SqlFunctions

SqlFunctions .DateDiff Method

something like this

products = (from a in db.Products
             where SqlFunctions.DateDiff("DAY", now, a.DateLowStock) >= 14).ToList()
    
answered by 07.11.2018 в 20:04