-4

I need to calculate the age of a person using the following: birthYear, curYear, birthMonth and curMonth.

my code is the following but it doesn't resolve in junit

    public int getApproxAge2(int birthYear, int curYear, int birthMonth, int curMonth)
{
    if (curMonth >= birthMonth)
    {
        return curYear - birthYear;
    }
    else 
    {
        return curYear - (birthYear-1);
    }

}

1 Answers1

0
return (curYear - birthYear - 1) > 0 ? (curYear - birthYear - 1) : 0;

This will make sure that you don't get negative age in case curYear and birthYear are the same.

instead of return curYear - (birthYear-1);

Say, you have your birthday in October and current month is May, then the logic should be you haven't reached your birth month.
Thus, you are one year less than the difference between current year and your birth year.

Devendra Lattu
  • 2,532
  • 2
  • 15
  • 25