1

I have two DateTime objects in C#, say birthDateTime and curDateTime.

Now, I want to calculate the year difference bewteen current datetime and someone's birthday. I want to do something like

int years = curDateTime- birthDateTime;
//If years difference is greater than 5 years, do something.
  if(years > 5)
    ....
Tony
  • 3,319
  • 12
  • 56
  • 71
  • 4
    possible duplicate of [How do I calculate someone's age in C#?](http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c) – Chris Van Opstal Nov 09 '10 at 00:31

5 Answers5

1

The subtraction operator will result in a TimeSpan struct. However, the concept of "years" does not apply to timespans, since the number of days in a year is not constant.

TimeSpan span = curDateTime - birthDateTime;
if (span.TotalDays > (365.26 * 5)) { ... }

If you want anything more precise than this, you will have to inspect the Year/Month/Day of your DateTime structs manually.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

Sounds like you are trying to calculate a person's age in the way people usually respond when asked for their age.

See Calculate age in C# for the solution.

Community
  • 1
  • 1
Jason Kresowaty
  • 16,105
  • 9
  • 57
  • 84
0

You can use AddYears method and check the condition if the Year property.

var d3 = d1.AddYears(-d2.Year);

if ((d1.Year - d3.Year) > 5)
{
    var ok = true;
}

You will need to handle invalid years, e.g. 2010 - 2010 will cause an exception.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
0
if (birthDateTime.AddYears(5) < curDateTime)
{
    // difference is greater than 5 years, do something...
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
0
DateTime someDate = DateTime.Parse("02/12/1979");
int diff = DateTime.Now.Year - someDate.Year;

This is it, no exceptions or anything...

Oakcool
  • 1,470
  • 1
  • 15
  • 33