简体   繁体   中英

how to find date range between two dates in days format using linq c#

I have a requirement for generating report in form of 15 days,30 days,45 days. I have to compare the list data which is coming from db with current date.example if difference is 5days. It is less than 15,so i should send to 15 days ,if >15 i should send to greater than 15etc.How to write linq query for this.can any one help on this please

I'm not sure that can be possible to make this in only one query. But, I can propose you another solution. Instead of one query, you can use one query for every case. In order to compare date difference, you can use SqlFunctions Class. For this, you should use :

   using System.Data.Objects.SqlClient; 

Here is the query for 5 days with an imaginary table and fields :

      var lstDiff5 = (from ro in dc.Commandes where
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) <= 5
                   select ro).ToList();

The DateDiff Function takes the date part (DD for days), the start date and the end date. In my case the start date is the current date. And for 15 days :

                var lstDiff15 = (from ro in dc.Commandes where
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) > 5 &&
                   SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) >= 15
                          select ro).ToList();

You can change the operators > et >= depending your need.

At the end, you can fill your report using all of your lists or you can merge your lists into a new list in order to bind your report to your final list.

You can use DaysBetween function in linq.It will return all dates betwee the given dates. Example: DateTime dt = DateTime.Today.Date.AddMonths(1); int d = dt.DaysBetween(DateTime.Today).ToList().Count; DateTime dt = DateTime.Today.Date.AddMonths(1); int d = dt.DaysBetween(DateTime.Today).ToList().Count;

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