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;
    }

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.

commented: my code now works. thanks to you +1

hey thanks! it works!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.