Calculating age with current date and birth date in Java

datetime, java

Solution

If you can use Java 8, it's much better than joda:

    LocalDate birthday = LocalDate.of(1982, 01, 29);
    long yearsDelta = birthday.until(LocalDate.now(), ChronoUnit.YEARS);
    System.out.println("yearsDelta = " + yearsDelta);

Problem

I'm just starting out with java, and i'm making a program that determines a person's car rental rates, based on age and gender. This method is calculating the person's age based off of the current date and their birth date. it sort of works, but there's a problem with borderline cases (for example sometimes it will say you're 25 when you're 24). How can i fix it to make it return the exact age instead of it saying you're 1 year older sometimes? (and please no Joda, i can't use it in this assignment) ``` public static int calcAge(int curMonth, int curDay, int curYear,int birthMonth,int birthDay,int birthYear) { int yearDif = curYear - birthYear; int age = 08; if(curMonth < birthMonth) { age = yearDif - 1; } if(curMonth == birthMonth) { if(curDay < birthDay) { age = yearDif - 1; } if(curDay > birthDay) { age = yearDif; } } if(curMonth > birthMonth) { age = yearDif; } return age; } ```

Original source