0

How can I subtract two calendar dates from each other.

For instance: 05-05-2014 minus 03-02-2013 and then it'll calculate the difference between the dates in years, months, hours and minutes.

SteveC
  • 15,808
  • 23
  • 102
  • 173
Napokue
  • 105
  • 13
  • Check this out: http://stackoverflow.com/questions/1607336/calculate-difference-between-two-dates-number-of-days – TheUser1024 Mar 14 '14 at 12:55
  • 1
    Use the "new DateTime()" then use the ".Subtract" routine. This is pretty basic and there are other stack questions about this. You might look around first before asking : ) – drew_w Mar 14 '14 at 12:56
  • @drew_w He may actually just take a language tutorial - this is likely one of the basic examples. – TomTom Mar 14 '14 at 12:58

2 Answers2

3

Maybe something like this:

var end=DateTime.Parse("05-05-2014");
var start=DateTime.Parse("03-02-2013");
TimeSpan difference=(end-start);

Or as in the comment. You can use DateTime.Subtract() like this:

TimeSpan difference=end.Subtract(start);

Edit

If you look at the DateTime class in the a reflector. You will find this:

public static TimeSpan operator -(DateTime d1, DateTime d2)
{
    return new TimeSpan(d1.InternalTicks - d2.InternalTicks);
}
public TimeSpan Subtract(DateTime value)
{
    return new TimeSpan(this.InternalTicks - value.InternalTicks);
}

Both the operator and the Subtract method uses the same code. So yes it is the same thing. It is just what you personally prefer.

Arion
  • 31,011
  • 10
  • 70
  • 88
1

Date can be substracted from one another, and will return a TimeSpan. You can access the value of the TimeSpan to find out its value in years, days, etc...

var ts = DateTime.Now - new DateTime(2014, 1, 1);
// ts.Days is the number of days between now and the first of january 2014
samy
  • 14,832
  • 2
  • 54
  • 82