Calculate difference between two dates (number of days)?

I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?


Solution 1:

Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays

Solution 2:

The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:

(EndDate.Date - StartDate.Date).Days

Again assuming StartDate and EndDate are of type DateTime.

Solution 3:

Use TimeSpan object which is the result of date substraction:

DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;