DateTime Subtraction

  • Thread starter Thread starter Shail
  • Start date Start date
S

Shail

I want to calculate the age of person from his date of
Date of Birth, normal subtractions of date gives hours,
how to get the age in years and months.
Thanks.
 
use the AddYears() and AddMonths() of the DateTime object, this will return
a DateTime object with that many years or months more or less depending on
what values (positive or negative) you passed as the argument to them..
 
I want to calculate the age of person from his date of
Date of Birth, normal subtractions of date gives hours,
how to get the age in years and months.

See the DateTime subtraction operator.
 
Subtracting two DateTime values results in a TimeSpan. A TimeSpan indicates
the number of days, but this can't be converted directly to years and months
because different years and months vary in length. This isn't a
straightforward problem because "age in months" is ambiguous. Your best bet
is probably to compare the Year, Month, and Day values of the two DateTime's
individually, e.g.

// the exact definition of "age in months" is open to interpretation
DateTime now = DateTime.Now;
int ageInMonths = 12 * (now.Year - birthdate.Year) + now.Month -
birthdate.Month;
int ageInYears = ageInMonths / 12;
int ageRemainderMonths = ageInMonths % 12;

Note that I stored DateTime.Now in a temporary variable instead of referring
to it twice. I think that's necessary because the year and/or month value of
DateTime.Now could change between two successive calls in the same
expression.
 
Back
Top