最近在写项目的时候遇到了一个需要根据出生日期计算年龄的问题,今天特意将代码记下来已被后期使用。
1 //根据出生日期计算年龄 2 public int getAgeByBirth(String birthDayStr) { 3 SimpleDateFormat sdf = new SimpleDateFormat( "yy-MM-dd" ); 4 Date birthDay= null; 5 try { 6 birthDay = sdf.parse(birthDayStr); 7 } catch (ParseException e) { 8 e.printStackTrace(); 9 } 10 // String str = sdf.format(parse( " 2005-06-09 00:00:00 " ); 11 12 13 int age = 0; 14 Calendar cal = Calendar.getInstance(); 15 if (cal.before(birthDay)) { //出生日期晚于当前时间,无法计算 16 throw new IllegalArgumentException( 17 "The birthDay is before Now.It's unbelievable!"); 18 } 19 int yearNow = cal.get(Calendar.YEAR); //当前年份 20 int monthNow = cal.get(Calendar.MONTH); //当前月份 21 int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期 22 cal.setTime(birthDay); 23 int yearBirth = cal.get(Calendar.YEAR); 24 int monthBirth = cal.get(Calendar.MONTH); 25 int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); 26 age = yearNow - yearBirth; //计算整岁数 27 if (monthNow <= monthBirth) { 28 if (monthNow == monthBirth) { 29 if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前,年龄减一 30 } else { 31 age--;//当前月份在生日之前,年龄减一 32 } 33 } 34 return age; 35 }
在调用的时候注意:
//根据修改过的出生日期从新计算被保险人的年龄tSaveLPInsuredSchema.setAge(String.valueOf(getAgeByBirth(mLPInsuredSchema.getBirthDay())));