简体   繁体   中英

Correct way to return results from linq to sql between dates

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 23:59:59

在此处输入图片说明

*in image the Imerominia = Date

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;
     }

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?

Thanks for your answers. I found how to do it. I simply used the addDays and addMilliseonds to get the right date. Here is the code for anyone who will need it.

    public List<Invoices> SearchInvoicesNotSendToMydata(DateTime fromDate, DateTime toDate)
    {
        List<Invoices> invoices = db.Invoices
                               .Where(p => (p.Date >= fromDate.Date 
                               && p.Date <= toDate.Date.AddDays(1).AddMilliseconds(-1)));
    
        return invoices;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM