【发布时间】:2015-12-22 08:21:42
【问题描述】:
我正在尝试计算占月数的 java 年龄,因此仅减去年数是行不通的。我还想告诉用户今天是否是他们的生日。这是我到目前为止的代码,但恐怕它有点偏离。即使它比较的两个日期相等,它也不会告诉今天是否是生日。我最初尝试计算的方式是使用毫秒。您看到 2 种获取当前日期的方法的原因是因为我正在尝试一些方法来使其正常工作,但想向所有人展示我的工作,以便他们可以为我指明正确的方向。
编辑澄清 我的意思是 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));
}
}
【问题讨论】:
-
澄清你所说的“数月”是什么意思你想要一个年龄是 22 岁零 4 个月,还是你只是说 2015-1993 可以是 22 岁或 21 岁,这取决于他们的生日今年已经过去了
-
道歉。我的意思是 2015-1993 可以是 22 岁或 21 岁,这取决于他们今年的生日是否已经过去
-
@alphamalle 请将此类附加信息或说明作为对您问题的编辑而不是作为评论发布。不要让你的读者这么努力。
标签: java android date calendar compareto