Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date difference in years using C# [duplicate]

Tags:

date

c#

datediff

How can I calculate date difference between two dates in years?

For example: (Datetime.Now.Today() - 11/03/2007) in years.

like image 627
msbyuva Avatar asked Nov 08 '10 19:11

msbyuva


People also ask

How can I compare two dates in C?

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

How do I get the difference between two dates and years in C#?

Use DateTime. Subtract to get the difference between two dates in C#.


2 Answers

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); 
like image 101
Richard J. Ross III Avatar answered Oct 05 '22 22:10

Richard J. Ross III


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); } 
like image 31
dana Avatar answered Oct 05 '22 22:10

dana