Java 使用出生日期计算年龄
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20091877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate the age using the date of birth
提问by roshanpeter
I am developing an android app to find the age from the date of birth provided by user.. three edit-texts are there one for day and other two for month and year. I got the code from this link.. But I dont know what to do next... I am giving the code so far I created... pls check and help me...
我正在开发一个 android 应用程序来查找用户提供的出生日期的年龄..三个编辑文本是一个用于日,另外两个用于月和年。我从这个链接得到了代码..但我不知道下一步该怎么做......我正在提供到目前为止我创建的代码......请检查并帮助我......
main_activity.xml
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
主活动.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;
}
}
采纳答案by gahfy
You should add a click listener to your button, then in it, calculate the age and display it in your TextView.
您应该为按钮添加一个单击侦听器,然后在其中计算年龄并将其显示在您的 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;
}
}
回答by pavanmvn
In button click just pass the values from edit text boxes to the method and display the return value in textview...
在按钮中单击只需将编辑文本框中的值传递给方法并在 textview 中显示返回值...
回答by Juboraj Sarker
First create a class:
首先创建一个类:
public class 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;
}
}
}
then simply call these method in your activity
然后只需在您的活动中调用这些方法
AgeCalculation age = new AgeCalculation ();
age.getCurrentDate();
age.setDateOfBirth(getYear, getMonth, getDate);
int calculatedYear = age.calcualteYear();
int calculatedMonth = age.calcualteMonth();
int calculatedDate = age.calcualteDay();
回答by Basil Bourque
tl;dr
tl;博士
Period.between(
LocalDate.of( Integer.parseInt( … ) , … , … ) , // ( year, month, dayOfMonth )
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
).getYears()
Details
细节
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
您正在使用麻烦的旧日期时间类,现在是遗留的,被 java.time 类取代。
The LocalDate
class represents a date-only value without time-of-day and without time zone.
该LocalDate
级表示没有时间一天和不同时区的日期,唯一的价值。
Unlike the legacy classes, the months have sane numbering, 1-12 for January-December.
与传统课程不同,月份有合理的编号,1-12 月为 1-12。
LocalDate localDate = LocalDate.of( Integer.parseInt( … ) , … , … ) ; // year , month , day
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Representing a span of time in granularity of days-months-years is done with the Period
class.
以天-月-年的粒度表示时间跨度是通过Period
类完成的。
Period age = Period.between( localDate , today );
To get a String in standard ISO 8601format, call age.toString()
. Or interrogate for each part, years, months, days.
要获取标准ISO 8601格式的字符串,请调用age.toString()
. 或询问每个部分,年,月,日。
int y = age.getYears();
int m = age.getMonths();
int d = age.getDays();
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。