使用出生日期计算年龄

时间:2013-11-20 09:23:35

标签: java android date

我正在开发一个Android应用程序来查找用户提供的出生日期的年龄。三个编辑文本是一天一个,另外两个月和年。我从这个link得到了代码..但是我不知道下一步该做什么......到目前为止我给的代码我创建了...请检查并帮助我...

main_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="32dp"
        android:layout_marginTop="42dp"
        android:ems="10"
        android:inputType="date" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:inputType="date" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="24dp"
        android:ems="10"
        android:inputType="date" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText3"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="82dp"
        android:onClick="getAge"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="54dp"
        android:text="TextView" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    long a =0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText et1 = (EditText) findViewById (R.id.editText1);
        EditText et2 = (EditText) findViewById (R.id.editText2);
        EditText et3 = (EditText) findViewById (R.id.editText3);
        Button btn1  = (Button)   findViewById (R.id.button1)  ;
        TextView tv1 = (TextView) findViewById (R.id.textView1);

    }


    public int getAge (int _year, int _month, int _day) {

        GregorianCalendar cal = new GregorianCalendar();
        int y, m, d, a;         

        y = cal.get(Calendar.YEAR);
        m = cal.get(Calendar.MONTH);
        d = cal.get(Calendar.DAY_OF_MONTH);
        cal.set(_year, _month, _day);
        a = y - cal.get(Calendar.YEAR);
        if ((m < cal.get(Calendar.MONTH))
                        || ((m == cal.get(Calendar.MONTH)) && (d < cal
                                        .get(Calendar.DAY_OF_MONTH)))) {
                --a;
        }
        if(a < 0)
                throw new IllegalArgumentException("Age < 0");
        return a;
}

}

4 个答案:

答案 0 :(得分:21)

您应该在按钮上添加一个点击监听器,然后在其中,计算年龄并在TextView中显示它。

public class MainActivity extends Activity {

    long a =0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText et1 = (EditText) findViewById (R.id.editText1);
        final EditText et2 = (EditText) findViewById (R.id.editText2);
        final EditText et3 = (EditText) findViewById (R.id.editText3);
        Button btn1  = (Button)   findViewById (R.id.button1)  ;
        final TextView tv1 = (TextView) findViewById (R.id.textView1);

        btn1.setOnClickListener(new OnClickListener{
            @Override
            public void onClick (View v){
                int day = Integer.parseInt(et1.getText().toString());
                int month = Integer.parseInt(et2.getText().toString());
                int year = Integer.parseInt(et3.getText().toString());

                tv1.setText(String.valueOf(MainActivity.this.getAge(year, month, day)));
            }
        });
    }


    public int getAge (int _year, int _month, int _day) {

        GregorianCalendar cal = new GregorianCalendar();
        int y, m, d, a;         

        y = cal.get(Calendar.YEAR);
        m = cal.get(Calendar.MONTH);
        d = cal.get(Calendar.DAY_OF_MONTH);
        cal.set(_year, _month, _day);
        a = y - cal.get(Calendar.YEAR);
        if ((m < cal.get(Calendar.MONTH))
                        || ((m == cal.get(Calendar.MONTH)) && (d < cal
                                        .get(Calendar.DAY_OF_MONTH)))) {
                --a;
        }
        if(a < 0)
                throw new IllegalArgumentException("Age < 0");
        return a;
    }

}

答案 1 :(得分:2)

在按钮中单击,只需将编辑文本框中的值传递给方法,并在textview中显示返回值...

答案 2 :(得分:2)

TL;博士

Period.between( 
    LocalDate.of( Integer.parseInt( … ) , … , … ) ,  // ( year, month, dayOfMonth )
    LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) 
).getYears()

详细

你正在使用麻烦的旧日期时间类,现在是旧的,取而代之的是java.time类。

LocalDate类表示没有时间且没有时区的仅限日期的值。

与传统课程不同,月份的数字是理智的,1月至12月是1-12。

LocalDate localDate = LocalDate.of( Integer.parseInt( … ) , … , … ) ;  // year , month , day

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

continent/region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用诸如ESTIST之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

使用Period类表示以天 - 月 - 年为单位的时间跨度。

Period age = Period.between( localDate , today );

要获得标准ISO 8601格式的字符串,请致电age.toString()。或询问每个部分,年,月,日。

int y = age.getYears();
int m = age.getMonths();
int d = age.getDays();

关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和&amp; SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 3 :(得分:0)

首先创建一个类:

公共类AgeCalculation {

private int startYear;
private int startMonth;
private int startDay;
private int endYear;
private int endMonth;
private int endDay;
private int resYear;
private int resMonth;
private int resDay;
private Calendar start;
private Calendar end;

public String getCurrentDate() {
    end = Calendar.getInstance();
    endYear = end.get(Calendar.YEAR);
    endMonth = end.get(Calendar.MONTH);
    endMonth++;
    endDay = end.get(Calendar.DAY_OF_MONTH);
    return endDay + ":" + endMonth + ":" + endYear;
}

public void setDateOfBirth(int sYear, int sMonth, int sDay) {
    startYear = sYear;
    startMonth = sMonth;
    startDay = sDay;

}

public int calcualteYear() {
    resYear = endYear - startYear;

    if (endMonth < startMonth){

        resYear --;

    }


    return resYear;

}

public int calcualteMonth() {
    if (endMonth >= startMonth) {
        resMonth = endMonth - startMonth;
    } else {
        resMonth = endMonth - startMonth;
        resMonth = 12 + resMonth;
        resYear--;
    }

    return resMonth;
}

public int calcualteDay() {

    if (endDay >= startDay) {
        resDay = endDay - startDay;
    } else {
        resDay = endDay - startDay;
        resDay = 30 + resDay;
        if (resMonth == 0) {
            resMonth = 11;
            resYear--;
        } else {
            resMonth--;
        }

    }

    return resDay;
}

public String getResult() {
    return resDay + ":" + resMonth + ":" + resYear;
}


public String dob (int sYear, int sMonth, int sDay) {
    startYear = sYear;
    startMonth = sMonth;
    startDay = sDay;

    return  startDay + "/" + startMonth + "/" + startYear;

}

}

然后只需在您的活动中调用这些方法

AgeCalculation age = new AgeCalculation ();
  age.getCurrentDate();
  age.setDateOfBirth(getYear, getMonth, getDate);
  int calculatedYear =  age.calcualteYear();
  int calculatedMonth = age.calcualteMonth();
  int calculatedDate = age.calcualteDay();