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

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

I tried using following code:
C#
  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>
Posted
Updated 1-Dec-15 10:12am
v2

Basically, you can subtract two DateTimes and get a TimeSpan as a result:
C#
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
 
v3
Try following:

C#
var days = from items in Vals
            select new
            {
                days = items.maxdate - items.mindate
            };

foreach (var day in days)
{
    Console.WriteLine(day.days.TotalDays);
}
 
Share this answer
 
v2
Comments
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-
C#
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);



-KR
 
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