Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating age with current date and birth date in Java

Tags:

java

datetime

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;
  }
like image 400
user3242445 Avatar asked Jan 27 '14 23:01

user3242445


2 Answers

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);
like image 98
user2684301 Avatar answered Sep 30 '22 00:09

user2684301


You need to check for equals when you are comparing the days e.g

else if (curDay >= birthDay) {
    age = yearDif;
}

instead of

if(curDay > birthDay) {
    age = yearDif;
}
like image 29
CheeseFerret Avatar answered Sep 30 '22 01:09

CheeseFerret