Advertisement
Advertisement


Calculate difference between two dates (number of days)?


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

2017/05/23
1
1132
5/23/2017 12:34:59 PM

Accepted Answer

Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays
2014/09/30
2094
9/30/2014 1:39:49 PM

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.

2020/04/06

Use TimeSpan object which is the result of date substraction:

DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
2009/10/22

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;
2009/10/22

DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
2013/11/03

In case someone wants numer of whole days as a double (a, b of type DateTime):

 (a.Date - b.Date).TotalDays
2014/06/13

Source: https://stackoverflow.com/questions/1607336
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]