0

Consider that i have list dtArray1 that consist of DateTime items I mean 10.10.2010, 10.10.2015 and so on.

Could u say me how find subract of this element ? How i can get diffeerence between 2 years?

for (Int32 index = 1; index < dtArray1.Count;index++)
{
    if (dtArray1[index] >= dtArray1[index - 1])
    {            
        dtArray1[index].Subtract(dtArray1[index - 1]);
        Console.WriteLine(dtArray1[index]);
        Console.ReadLine();
     }
}
  • What does your current code actually do? What errors does it produce? What output does it produce? – Arran Nov 11 '13 at 09:37
  • 2
    _"diffeerence between 2 years"_?? – Tim Schmelter Nov 11 '13 at 09:37
  • i should get in the output 5 years difference between 10.10.2015 and 10.10.2010 but i get 10.10.2015 – user2960284 Nov 11 '13 at 09:42
  • 1
    After your last edit the code makes even less sense. Now you are subtrating two datetimes without assigning the result to a variable. `Console.WriteLine(dtArray1)` is pointless since `dtArray1` is a collection. Why have you edited your code in this way? – Tim Schmelter Nov 11 '13 at 09:45

1 Answers1

2

If your dates are of the DateTime type, you can just substract one from the other, like so:

var span = dtArray1[index] - dtArray1[index - 1];
Console.WriteLine(span.Days); // prints "1836" 

The result will be of type TimeSpan. TimeSpan does not have a Years property, so you'll have to calculate the number of years yourself, keeping in mind leap years and whatnot. See How do I calculate someone's age in C#?

Community
  • 1
  • 1
Rik
  • 28,507
  • 14
  • 48
  • 67