android计算据当前时间的天数和年龄

计算天数:public static int daysBetween(String bdate) throws ParseException{ 
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
Calendar cal = Calendar.getInstance(); 
cal.setTime(sdf.parse(sdf.format(new Date()))); 
long time1 = cal.getTimeInMillis(); 
cal.setTime(sdf.parse(bdate)); 
long time2 = cal.getTimeInMillis(); 
long between_days=(time1-time2)/(1000*3600*24); 


return Integer.parseInt(String.valueOf(between_days)); 

计算年龄:public static String getAgeByBirth(String birth) {
Date birthDay = null;
if (birth == null) {
return "";
}
SimpleDateFormat format = null;
if (birth.contains("/")) {
format = new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);
} else {
format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
}
try {
birthDay = format.parse(birth);
} catch (ParseException e) {
e.printStackTrace();
return "";
}
Calendar cal = Calendar.getInstance();


if (cal.before(birthDay)) {
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}


int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);


int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);


int age = yearNow - yearBirth;


if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
// monthNow==monthBirth
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
} else {
// do nothing
}
} else {
// monthNow>monthBirth
age--;
}
} else {
// monthNow// donothing
}


return age + "";
}

你可能感兴趣的:(android计算据当前时间的天数和年龄)