【发布时间】:2013-12-23 16:23:17
【问题描述】:
我想得到两个日期之间的月数。日期是某人的生日和当前日期。所以我得到两个日期之间的年数,而不是月数..
假设我的日期是 06/09/2011 和 06/11/2012。所以我希望答案是 1 年 2 个月。我得到了年份,但没有月份。请帮忙。下面是获取年数的代码
public int getAge(Date dateOfBirth) {
today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
month = today.get(Calendar.MONTH) - birthDate.get(Calendar.MONTH);
if ( (birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3) ||
(birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH ))){
days = birthDate.get(Calendar.DAY_OF_MONTH) - today.get(Calendar.DAY_OF_MONTH);
age--;
Toast.makeText(getApplicationContext(), "inside if", Toast.LENGTH_SHORT).show();
Log.e("month is",month+"");
Log.e("Days",days+ " left");
}else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH )) &&
(birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH ))){
Toast.makeText(getApplicationContext(), "inside else if", Toast.LENGTH_SHORT).show();
age--;
}
return age;
【问题讨论】:
-
查看我的答案并尝试一下。
-
在发帖前尝试搜索。在 StackOverflow.com 上多次回答。专注于 Joda-Time,其中包括完全符合您目的的课程。从阅读问题开始,Joda-Time: what's the difference between Period, Interval and Duration?。
-
我没有使用 joda time,所以我正在寻找替代方案
标签: java date date-difference