Reputation: 81
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;
}
Upvotes: 5
Views: 14210
Reputation: 617
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;
}
Upvotes: 4
Reputation: 2620
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);
Upvotes: 8
Reputation: 165
You can try to use "Date" to convert both times to epoch milliseconds and then simply subtract these and get the difference converted back to year values by simple math. Get it? This would be without any extra libraries :)
Upvotes: 0