Last active
July 17, 2020 01:25
-
-
Save ralphgabrielle/faa5d429c2d554ac70533663af18c4fc to your computer and use it in GitHub Desktop.
AgeCalculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AgeCalculator { | |
private int days; | |
private int months; | |
private int years; | |
AgeCalculator(int days, int months, int years) { | |
this.days = days; | |
this.months = months; | |
this.years = years; | |
} | |
public int getDays() { | |
return days; | |
} | |
public int getMonths() { | |
return months; | |
} | |
public int getYears() { | |
return years; | |
} | |
public boolean isAboveMinimumAgeRequirement() { | |
return getYears() >= 18; | |
} | |
@Override | |
public String toString() { | |
return years + " Years, " + months + " Months, " + days + " Days"; | |
} | |
public static AgeCalculator calculateAge(Calendar birthDay) { | |
int years; | |
int months; | |
int days; | |
long currentTime = System.currentTimeMillis(); | |
Calendar now = Calendar.getInstance(); | |
now.setTimeInMillis(currentTime); | |
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR); | |
int currMonth = now.get(Calendar.MONTH) + 1; | |
int birthMonth = birthDay.get(Calendar.MONTH) + 1; | |
months = currMonth - birthMonth; | |
//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; | |
} | |
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; | |
} | |
} | |
return new AgeCalculator(days, months, years); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment