Calculate difference between two dates (number of days)? – Dev

The best answers to the question “Calculate difference between two dates (number of days)?” in the category Dev.

QUESTION:

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#?

ANSWER:

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.

ANSWER:

Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays

ANSWER:

I think this will do what you want:

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);

TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;

ANSWER:

Use TimeSpan object which is the result of date substraction:

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