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.
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.
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.
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