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,209
  • 12
  • 53
  • 70
  • 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
  • 144,362
  • 22
  • 272
  • 285
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
  • 15,657
  • 9
  • 56
  • 83
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
  • 94,090
  • 80
  • 289
  • 441
0
if (birthDateTime.AddYears(5) < curDateTime)
{
    // difference is greater than 5 years, do something...
}
LukeH
  • 252,910
  • 55
  • 358
  • 405
0
DateTime someDate = DateTime.Parse("02/12/1979");
int diff = DateTime.Now.Year - someDate.Year;

This is it, no exceptions or anything...

Oakcool
  • 1,472
  • 1
  • 15
  • 32