这不是.TotalDays
,因为少于24小时的周期可能会通过重叠两个不同的天来返回“ 2”。同样,相隔两个日期仍然应该返回“ 1”。
例如:
2012-2-1 14:00 to 2012-2-2 23:00 -> 2 (1st and 2nd Feb)
2012-2-1 14:00 to 2012-2-2 10:00 -> 2 (1st and 2nd Feb)
2012-2-1 23:00 to 2012-2-2 00:00 -> 2 (1st and 2nd Feb)
2012-2-1 23:00 to 2012-2-3 00:00 -> 3 (1st, 2nd, 3rd Feb)
2012-2-1 14:00 to 2012-2-1 15:00 -> 1 (1st Feb)
2012-2-1 14:00 to 2012-2-1 14:00 -> 1 (1st Feb)
2012-1-1 00:00 to 2012-12-31 23:59 -> 366 (All of 2012)
我可以通过以下代码获得此功能:
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;
有更好的方法吗?
为什么不仅是:
int count = dt1.Date.Subtract(dt2.Date).Duration().Days + 1;
使用
.Date