Skip to content

Instantly share code, notes, and snippets.

@Kishanjvaghela
Created May 23, 2016 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kishanjvaghela/f8a354177bef912f9cb4d60e20465a71 to your computer and use it in GitHub Desktop.
Save Kishanjvaghela/f8a354177bef912f9cb4d60e20465a71 to your computer and use it in GitHub Desktop.
AgeCalculator
public class Age {
private int days;
private int months;
private int years;
public Age(int days, int months, int years) {
this.days = days;
this.months = months;
this.years = years;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
}
public static Age calculateAge(Date birthDate) {
int years = 0;
int months = 0;
int days = 0;
//create calendar object for birth day
Calendar birthDay = Calendar.getInstance();
birthDay.setTimeInMillis(birthDate.getTime());
//create calendar object for current day
long currentTime = System.currentTimeMillis();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(currentTime);
//Get difference between years
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
int currMonth = now.get(Calendar.MONTH) + 1;
int birthMonth = birthDay.get(Calendar.MONTH) + 1;
//Get difference between months
months = currMonth - birthMonth;
//if month difference is in negative then reduce years by one and calculate the number of months.
if (months < 0) {
years--;
months = 12 - birthMonth + currMonth;
if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
months--;
} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
years--;
months = 11;
}
//Calculate the days
if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
int today = now.get(Calendar.DAY_OF_MONTH);
now.add(Calendar.MONTH, -1);
days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
} else {
days = 0;
if (months == 12) {
years++;
months = 0;
}
}
//Create new Age object
return new Age(days, months, years);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment