如何在android中创建年龄计算方法 [英] How to create method for age calculation method in android

查看:258
本文介绍了如何在android中创建年龄计算方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个方法来计算出生日期的年龄,逻辑是否正确以及如何在android Java中编写它:

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


推荐答案

这是我的解决方案问题:

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

我使用了 DatePicker 获取此处所需的输入值。此方法与日期选择器一起专门用于获取用户的DoB并计算其年龄。可以进行轻微修改以允许用户DoB的String输入,具体取决于您的具体实现。 String的返回类型用于更新TextView,可以使用一个轻微的mod来允许类型 int 输出。

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.

这篇关于如何在android中创建年龄计算方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆