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
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;
    }
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by scias23
1

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.

Votes + Comments
my code now works. thanks to you
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.