Count the number of dates between two dates

Posted by Matt Mitchell on Stack Overflow See other posts from Stack Overflow or by Matt Mitchell
Published on 2012-12-20T10:57:49Z Indexed on 2012/12/20 11:02 UTC
Read the original article Hit count: 203

Filed under:
|
|

I'm looking to count the dates covered (inclusive) between two DateTimes (not .TotalDays)

For example:

2012-2-1 14:00 to 2012-2-2 23:00 -> 2
2012-2-1 14:00 to 2012-2-2 10:00 -> 2
2012-2-1 14:00 to 2012-2-1 15:00 -> 1
2012-1-1 00:00 to 2012-12-31 23:59 -> 366

I can get this functionality with the code below:

DateTime dt1 = new DateTime(2000,1,2,12,00,00);
DateTime dt2 = new DateTime(2000,1,3,03,00,00);

int count = 0;
for (DateTime date = dt1; date.Date <= dt2.Date; date = date.AddDays(1))
    count++;

return count;

Is there a better way?

© Stack Overflow or respective owner

Related posts about c#

Related posts about date