Home > front end >  Correct way to return results from linq to sql between dates
Correct way to return results from linq to sql between dates

Time:11-14

I have a little problem with a query.

I have two datetime textboxes and a button to search.

When I search let's say from 12/08/2021 to 12/08/2021 it returns only one result which has date 2021-08-12 00:00:00.000 because the time on the other invoices is 2021-08-12 17:38:55.740

My code is:

    SearchInvoicesNotSendToMydata(fromDateEdit.DateTime, toDateEdit.DateTime);

    public List<Invoices> SearchInvoicesNotSendToMydata(DateTime fromDate, DateTime toDate)
     {
       List<Invoices> invoices = db.Invoices.Where(p => (p.Date >= fromDate && p.Date <= toDate));

       return invoices;
     }

The two variables have values

fromDate =12/8/2021 12:00:00

toDate = 12/8/2021 12:43:21

I know that it doesnt return the other invoices because of the time, I just want to know if there is an elegant way to return all invoices from date 0:00:00 to 12:00:00

enter image description here

*in image the Imerominia = Date

CodePudding user response:

In a quick way, you can do something like this. so it'll only check and compare with dates but no time.

public List<Invoices> SearchInvoicesNotSendToMydata(DateTime fromDate, DateTime toDate)
     {
       List<Invoices> invoices = db.Invoices.Where(p => (p.Date.Date >= fromDate.Date && p.Date.Date <= toDate.Date));

       return invoices;
     }

CodePudding user response:

If you want to make sure to include always a date from 00:00:00 to 12:00:00

The Date member of the DateTime class will give you a new DateTime instance, with the Hour at 00:00:00

SearchInvoicesNotSendToMydata(fromDateEdit.DateTime, toDateEdit.DateTime);

public List<Invoices> SearchInvoicesNotSendToMydata(DateTime fromDate, DateTime toDate)
{
    List<Invoices> invoices = db.Invoices.Where(p => (p.Date >= fromDate.Date && p.Date <= toDate.Date.AddHours(12)));

    return invoices;
}

For a real answer, a better spec is needed.

I just want to know if there is an elegant way to return all invoices from date 0:00:00 to 12:00:00

What happens if the two dates are not identical for instance?

  • Related