Android学习之计算2个日期之间有多少年月日

 我来答
若以下回答无法解决问题,邀请你更新回答
八维教育
2016-11-29 · 学高端技术就来八维教育
八维教育
北京八维教育是位于首都中关村上地信息产业园区的一所民办非学历高等教育机构。课程设置以市场需求为导向、以岗位要求为标准、为企业量身打造符合企业和市场需求的专业型人才。
向TA提问
展开全部
话不多说,上代码:
private void getAge(String birthday, String time, TextView tvAgeYear, TextView tvAgeMonth, TextView tvAgeDay) {
SimpleDateFormat formatBirthday = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
int yearBirthday = 0, monthBirthday = 0, dayBirthday = 0;
try {
Date dateBirthday = formatBirthday.parse(birthday);
Calendar calendarBirthday = Calendar.getInstance();
calendarBirthday.setTime(dateBirthday);
yearBirthday = calendarBirthday.get(Calendar.YEAR);
monthBirthday = calendarBirthday.get(Calendar.MONTH);
dayBirthday = calendarBirthday.get(Calendar.DAY_OF_MONTH);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatMoment = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Calendar calendarMoment = Calendar.getInstance();
int yearMoment = 0, monthMoment = 0, dayMoment = 0;
try {
Date dateMoment = formatMoment.parse(time);
calendarMoment.setTime(dateMoment);
yearMoment = calendarMoment.get(Calendar.YEAR);
monthMoment = calendarMoment.get(Calendar.MONTH);
dayMoment = calendarMoment.get(Calendar.DAY_OF_MONTH);
} catch (ParseException e) {
e.printStackTrace();
}
if (yearBirthday > yearMoment || yearBirthday == yearMoment && monthBirthday > monthMoment || yearBirthday == yearMoment && monthBirthday == monthMoment && dayBirthday > dayMoment) {
tvAgeYear.setText("??年");
tvAgeMonth.setText("??月");
tvAgeDay.setText("??天");
} else {
int yearAge = yearMoment - yearBirthday;
int monthAge = monthMoment - monthBirthday;
int dayAge = dayMoment - dayBirthday;
//按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减
if (dayAge < 0) {
monthAge -= 1;
calendarMoment.add(Calendar.MONTH, -1);//得到上一个月,用来得到上个月的天数
dayAge = dayAge + calendarMoment.getActualMaximum(Calendar.DAY_OF_MONTH);
}
if (monthAge < 0) {
monthAge = (monthAge + 12) % 12;
yearAge--;
}
String year, month, day;
if (yearAge < 10) {
year = "0" + yearAge + "年";
} else {
year = yearAge + "年";
}
if (monthAge < 10) {
month = "0" + monthAge + "月";
} else {
month = monthAge + "月";
}
if (dayAge < 10) {
day = "0" + dayAge + "天";
} else {
day = dayAge + "天";
}
tvAgeYear.setText(year);
tvAgeMonth.setText(month);
tvAgeDay.setText(day);
}
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式