How can I calculate date difference between two dates in years?
For example: (Datetime.Now.Today() - 11/03/2007)
in years.
Consider the problem of comparison of two valid dates d1 and d2. There are three possible outcomes of this comparison: d1 == d2 (dates are equal), d1 > d2 (date d1 is greater, i.e., occurs after d2) and d1 < d2(date d1 is smaller, i.e., occurs before d2).
Use DateTime. Subtract to get the difference between two dates in C#.
I have written an implementation that properly works with dates exactly one year apart.
However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.
So without further ado, here is the code:
DateTime zeroTime = new DateTime(1, 1, 1); DateTime a = new DateTime(2007, 1, 1); DateTime b = new DateTime(2008, 1, 1); TimeSpan span = b - a; // Because we start at year 1 for the Gregorian // calendar, we must subtract a year here. int years = (zeroTime + span).Year - 1; // 1, where my other algorithm resulted in 0. Console.WriteLine("Yrs elapsed: " + years);
Use:
int Years(DateTime start, DateTime end) { return (end.Year - start.Year - 1) + (((end.Month > start.Month) || ((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With