15,747,513 members
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

## Solution 1

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.

v3

## Solution 2

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

v2
Comments
apr1234 2-Dec-15 10:44am
Thank you Debashish, it worked!
debashishPaul 2-Dec-15 16:43pm
Happy to help...

## Solution 3

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

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

Top Experts
Last 24hrsThis month
 Richard MacCutchan 60 Graeme_Grant 45 raddevus 10 Mordac the Preventer -6 hans.sch -6
 OriginalGriff 135 Graeme_Grant 110 Richard MacCutchan 60 Mordac the Preventer 10 hans.sch -6

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