tags:

views:

71

answers:

4

We want to find the number of days between two dates. This is simple when the dates are in the same year.

Is there a built-in way to do this if the dates are in different years, or do we just have to loop through each year?

+8  A: 

Subtracting a date from another yields a TimeSpan. You can use this to determine the number of whole days using the Days property, or whole and fractional days using the TotalDays property.

DateTime start = ...;
DateTime end = ...;

int wholeDays = (end - start).Days;

or

double totalAndPartialDays = (end - start).TotalDays;
Adam Robinson
+1 for mentioning `TotalDays`.
Abel
+3  A: 

you can probably do something like:

TimeSpan ts = endDate - startDate;
ts.Days
John Boker
+1  A: 

What are you missing?

DateTime - DateTime => Timespan

and Timespan has Days and TotalDays properties.

leppie
A: 
    DateTime date1 = DateTime.Now;
    DateTime date2 = new DateTime(date1.Year - 2, date1.Month, date1.Day);

    Int32 difference = date1.Subtract(date2).Days;
Piotr Justyna