1

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?

Abel
  • 54,106
  • 22
  • 138
  • 236
Shiraz Bhaiji
  • 62,289
  • 31
  • 137
  • 240

4 Answers4

15

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
  • 177,794
  • 32
  • 275
  • 339
3

you can probably do something like:

TimeSpan ts = endDate - startDate;
ts.Days
John Boker
  • 80,803
  • 17
  • 95
  • 130
1

What are you missing?

DateTime - DateTime => Timespan

and Timespan has Days and TotalDays properties.

leppie
  • 112,162
  • 17
  • 191
  • 293
0
    DateTime date1 = DateTime.Now;
    DateTime date2 = new DateTime(date1.Year - 2, date1.Month, date1.Day);

    Int32 difference = date1.Subtract(date2).Days;
Piotr Justyna
  • 4,622
  • 3
  • 23
  • 40