Home » Ado.Net » Entity Framework » Linq to Entity to get the number of day between two dates

Linq to Entity to get the number of day between two dates

If you want to have the amount of day between two dates, you can get those dates back to C# and do the difference between them. However, it is possible to tell Sql Server to do it for you by Linq To Entity.

It has change since Entity Framework (EF) 6. You have to use DbFunctions class now to execute complex operations to Sql Server.

The operation that interest us is named DiffDays. It takes two parameters. The first one is the smallest date, the second one is the biggest date. If you invert these parameters, the count will be negative.

Here is an example of use:

 var allActiveContest = GetAllActiveContestForUser(userId)
                .Select(d=>new ContestWithSmallStatistics(){
                               NumberOfDaysRemainingBeforeEndDate = DbFunctions.DiffDays(d.RegistrationRules.StartingTime,d.RegistrationRules.EndingTime).Value,
                               NumberOfUsersRegistered = d.Contester.Count

The main advantage is that you can have from the database exactly what you want instead of having a class that would have two dates. You could also use it for having some logics that will not return everything. For example, we could return only Active Contest for contest that has more than 30 days.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

4 Responses so far.

  1. Frédérick Roy says:

    Nice feature que je n’avais pas vu. A ajouter dans ma pensine 😉

  2. user says:

    Really nice sharing. Thank you for preparing.

  3. hap says:

    Really nice sharing. Thank you for preparing.

  4. Muhammad Rizwan says:

    thanx alot brother where ever you are. u done my day. ALLAH bless you. i spend two days and finally get you

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.