Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

java - How to create method for age calculation method in android

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...