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
  • 56,041
  • 24
  • 146
  • 247
Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252

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
  • 182,639
  • 35
  • 285
  • 343
3

you can probably do something like:

TimeSpan ts = endDate - startDate;
ts.Days
John Boker
  • 82,559
  • 17
  • 97
  • 130
1

What are you missing?

DateTime - DateTime => Timespan

and Timespan has Days and TotalDays properties.

leppie
  • 115,091
  • 17
  • 196
  • 297
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,888
  • 3
  • 25
  • 40