你好我正在创建一个Android应用程序,其中我有两个不同的日期现在我想要获得这些日期之间的年数任何人请帮助我如何做到这一点?这是我的代码
String birthday=p.getString("BirthDay");
Log.i("bd", String.valueOf(birthday));
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy");
final String formattedDate = df.format(c.getTime());
Log.i("formattedDate", String.valueOf(formattedDate));
凡生日保存日期,且格式化日期为当前日期,我希望这些
之间存在差异答案 0 :(得分:1)
请尝试此代码
String birthday = p.getString("BirthDay");
Calendar calendarBirthday = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy");
calendarBirthday.setTime(sdf.parse(birthday));
Calendar calendarNow = Calendar.getInstance();
int yearNow = calendarNow.get(Calendar.YEAR);
int yearBirthday = calendarBirthday.get(Calendar.YEAR);
int years = yearNow - yearBirthday;
答案 1 :(得分:-1)
int getYear(Date date1,Date date2){
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
Integer.parseInt(simpleDateformat.format(date1));
return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));
}
答案 2 :(得分:-1)
通过你的出生日期
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) + 1;
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;
}