我试图计算java中考虑了几个月的年龄,所以减去几年就不行了.我还想告诉用户今天是他们的生日.这是我到目前为止的代码,但我担心它有点偏.它也不会告诉今天是否是生日,即使它比较的两个日期是相等的.我试图最初计算的方式是使用毫秒.你看到获得当前日期的两种方法的原因是因为我正在尝试让它工作,但是想向每个人展示我的工作,以便他们能够指出我正确的方向.
编辑澄清
我的意思是2015-1993可以是22岁或21岁,这取决于他们今年的生日已经过去了.我想确保在考虑到这一点后得到正确的年龄.
public class ShowAgeActivity extends AppCompatActivity {
private TextView usersAge;
private static long daysBetween(Date one, Date two)
{
long difference = (one.getTime()-two.getTime())/86400000; return Math.abs(difference);
}
private Date getCurrentForBirthday()
{
Date birthday = (Date) this.getIntent().getExtras().get("TheBirthDay");
int birthdayYear = birthday.getYear() + 1900;
Calendar cal = Calendar.getInstance();
cal.set(birthdayYear, Calendar.MONTH, Calendar.DAY_OF_MONTH);
Date current = cal.getTime();
return current;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_age);
Date birthday = (Date) this.getIntent().getExtras().get("TheBirthDay");
Date currentDay = Calendar.getInstance().getTime();
long age = daysBetween(birthday,currentDay)/365;
usersAge =(TextView)findViewById(R.id.ageTextView);
if (birthday.compareTo(getCurrentForBirthday()) == 0 )
{
usersAge.setText("It is your birthday, and your Age is " + String.valueOf(age));
}
usersAge.setText("Your Age is " + String.valueOf(age));
}
}
解决方法:
下面是一个如何计算一个人的年龄的例子,如果今天是他们的生日,以及如果今天不是他们的生日,那么使用新的java.time包类作为其中一部分包括Java 8.
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1982, 9, 26);
LocalDate thisYearsBirthday = birthday.with(Year.now());
long age = ChronoUnit.YEARS.between(birthday, today);
if (thisYearsBirthday.equals(today))
{
System.out.println("It is your birthday, and your Age is " + age);
}
else
{
long daysUntilBirthday = ChronoUnit.DAYS.between(today, thisYearsBirthday);
System.out.println("Your age is " + age + ". " + daysUntilBirthday + " more days until your birthday!");
}