java计算年龄
?
?
精確到天計算年齡
public static int getAgeByCardId(String card) throws Exception {Integer len = card.length();if (len == CHINA_ID_MIN_LENGTH) {card = conver15CardTo18(card);}String birthDate = card.substring(6, 14);SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Date date = sdf.parse(birthDate); return calcAge(date);}/*** 由出生日期獲得年齡 精確到天* @param birthDay* @return* @throws Exception*/public static int calcAge(Date birthDay) throws Exception { Calendar cal = Calendar.getInstance(); if (cal.before(birthDay)) { throw new IllegalArgumentException("出生日期不能晚于當前日期"); } 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) { if (dayOfMonthNow < dayOfMonthBirth) age--; }else{ age--; } } return age; }?
?
按年計算年齡
/*** 根據身份編號獲取年齡* * @param idCard* 身份編號* @return 年齡*/public static int getAgeByIdCard(String idCard) {int iAge = 0;if (idCard.length() == CHINA_ID_MIN_LENGTH) {idCard = conver15CardTo18(idCard);}String year = idCard.substring(6, 10);Calendar cal = Calendar.getInstance();int iCurrYear = cal.get(Calendar.YEAR);iAge = iCurrYear - Integer.valueOf(year);return iAge;}?
總結
- 上一篇: React Native 轻松集成分享功
- 下一篇: 深入理解 GCD