I want to write a method to calculate the age from the birth date, is the logic correct and how to write it in android Java:
public int calculateAge(String birthday){
// consider that birthday format is ddmmyyyy;
String today = SystemDate(ddmmyyyy);
int bDay = birthday(1,2).toInteger;
int bMonth = birthday(3,4).toInteger;
int bYear = birhtday(5,8).toInteger;
int tDay = today(1,2).toInteger;
int tMonth = today(3,4).toInteger;
int tYear = today(5,8).toInteger;
if (tMonth == bMonth){
if (tday>= bDay){
age = tYear - bYear;
else
age = tYear - bYear - 1;}
else
if (tMonth > bMonth) {
age = tYear - bYear;
else
age = tYear - bYear - 1;}
}
return age;
}
The method of calculating age involves the comparison of a person's date of birth with the date on which the age needs to be calculated. The date of birth is subtracted from the given date, which gives the age of the person. Age = Given date - Date of birth.
You can use the DIFF function to calculate the age based on the date of birth entered by the user. To use this feature, you need our Gsuite addon. Install this addon to customize Google Forms.
The most basic way of calculating age is to use DATE_DIFF function to get the number of years between two dates. However, this function just subtracts the years, regardless if the date of birth has already passed or not, which is entirely inaccurate.
Here is my solution to the problem:
/**
* Method to extract the user's age from the entered Date of Birth.
*
* @param DoB String The user's date of birth.
*
* @return ageS String The user's age in years based on the supplied DoB.
*/
private String getAge(int year, int month, int day){
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
I used a DatePicker to get the input values required here. This method, together with the date picker, is specifically to get the user's DoB and calculate their age. A slight modification can be made to allow for String input(s) of the user's DoB, depending upon your specific implementation. The return type of String is for updating a TextView, a slight mod can be made to allow for type int
output also.
This works Perfectly.....
public int getAge(int DOByear, int DOBmonth, int DOBday) {
int age;
final Calendar calenderToday = Calendar.getInstance();
int currentYear = calenderToday.get(Calendar.YEAR);
int currentMonth = 1 + calenderToday.get(Calendar.MONTH);
int todayDay = calenderToday.get(Calendar.DAY_OF_MONTH);
age = currentYear - DOByear;
if(DOBmonth > currentMonth) {
--age;
} else if(DOBmonth == currentMonth) {
if(DOBday > todayDay){
--age;
}
}
return age;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With