Click here to Skip to main content
15,747,513 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

How to calculate the date difference of two dates and get the final difference amount.

I tried using following code:
  var tdays = from items in Vals
                           select new
                               days = 
                               DbFunctions.DiffDays(items.maxdate, items.mindate )

But I am getting error:
<pre lang="C#">base = {&quot;This function can only be invoked from LINQ to Entities.&quot;}</pre>
Updated 1-Dec-15 10:12am

Basically, you can subtract two DateTimes and get a TimeSpan as a result:
DateTime start = new DateTime(2015, 12, 1, 20, 0, 0);
DateTime end = new DateTime(2015, 12, 2, 4, 30, 10);
TimeSpan span = end - start;
int hours = span.Hours; // hours = 8;
int minutes = span.Minutes; // minutes = 30;
int seconds = span.Seconds; // seconds = 10;
int days = span.Days; // days = 0;
double totalDays = span.TotalDays; // totalDays = 0.35428241

You can find find more informations on TimeSpan structure here:
MSDN: TimeSpan Structure[^]

To answer to your question, we would need to know which type your Vals variable is an enumeration of; and if this type is not a common one (i.e., you defined it yourself), we would need to know how its maxdate and mindate members are defined.
Share this answer
Try following:

var days = from items in Vals
            select new
                days = items.maxdate - items.mindate

foreach (var day in days)
Share this answer
apr1234 2-Dec-15 10:44am    
Thank you Debashish, it worked!
debashishPaul 2-Dec-15 16:43pm    
Happy to help...
Rather do it this way-
DateTime oldDate = new DateTime(2015,11,2);
DateTime newDate = DateTime.Now;
TimeSpan ts = newDate - oldDate;
int differenceInDays = ts.Days;

Console.WriteLine("Total days: {0} ", differenceInDays);

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900