tags:

views:

197

answers:

3

I've been trying many ways to calculate the round number of days between two dates, I mean, counting the whole days. An example of what I need:

   START DATE            END DATE          Day Count  

24/02/2010 16:26     24/02/2010 16:26         1  
20/02/2010 18:16     24/02/2010 16:26         5  
31/12/2009 20:00     24/02/2010 16:26         56  
15/07/2009 20:59     24/02/2010 16:26         225  
+7  A: 

You can use the subtraction operator on the two instances of DateTime (or DateTimeOffset, as it has the same subtraction operator, and it is the recommended structure to use for date values in .NET) to get a TimeSpan instance.

Once you have that, you can call the Days property to get the number of whole days that the TimeSpan represents.

If you want the number of whole and fractional days, then look at the TotalDays property.

In your specific case, it seems that you want to add 1 to whatever value the Days property returns, as your custom calculation indicates that for two DateTime instances that represent the same value, the result is 1.

casperOne
+5  A: 

DateTime's can be subtracted to get a TimeSpan. The TimeSpan has a TotalDays which is the number of days (includes fractional days as well). Converting to int will round to the nearest integer.

int DaysBetween(DateTime d1, DateTime d2) {
    TimeSpan span = d2.Subtract(d1);
    return (int)span.TotalDays;
}
Josh Einstein
My solution in VB.NET: Dim ts As TimeSpan ts = s.Subtract(DateTime.Parse(h)) Dim days As Integer days = ts.TotalDays + 1
benoror
+2  A: 
DateTime dtOne;
DateTime dtTwo;

// to get the total days in between
int answer = (dtTwo - dtOne).TotalDays
mjmarsh
`TimeSpan.TotalDays` returns a double, so you'll need a conversion to `int` in there.
ChrisF