954,162 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

age compute using calendar class [problem]

i just can't figure out what's wrong with this.

1. suppose i enter 9-3-1991 as the birthdate, this should return 18. but it returns 17. //wrong
2. suppose i enter 2-9-1991 as the birthdate, this returns 18. //correct

what's wrong with my code?

private static int ageCalc(int mm, int dd, int yyyy) {

        Calendar currentDate = Calendar.getInstance();
        Calendar birthDate = new GregorianCalendar();

        birthDate.set(yyyy, mm, dd);

        age = currentDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);

        birthDate.add(Calendar.YEAR, age);
        
        if(currentDate.before(birthDate)) {
            age--;
        }

        return age;
    }
scias23
Junior Poster in Training
69 posts since Jan 2009
Reputation Points: 11
Solved Threads: 0
 

i just can't figure out what's wrong with this.

1. suppose i enter 9-3-1991 as the birthdate, this should return 18. but it returns 17. //wrong

private static int ageCalc(int mm, int dd, int yyyy){
// code
birthDate.set(yyyy, mm, dd);

I'd have to see the function call, but if you are doing this:

ageCalc (9, 3, 1991)


and passing 9 to the function as mm, realize that 9 is October, not September. January to December are 0 to 11, not 1 to 12. http://java.sun.com/javase/6/docs/api/constant-values.html#java.util.Calendar.SEPTEMBER

If you scroll to SEPTEMBER, you'll see that it is equal to 8.

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

hey thanks! it works!

scias23
Junior Poster in Training
69 posts since Jan 2009
Reputation Points: 11
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You