如何在Android中创建年龄计算方法的方法


问题内容

我想编写一种从出生日期开始计算年龄的方法,逻辑是否正确以及如何在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;
}

问题答案:

这是我对问题的解决方案:

/**
 * 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;  
}

我使用DatePicker获取此处所需的输入值。此方法与日期选择器一起专门用于获取用户的DoB并计算其年龄。根据您的特定实现,可以进行少许修改以允许用户DoB的String输入。String的返回类型是用于更新TextView的,可以稍作修改以允许类型int输出。