|
@@ -424,4 +424,40 @@ public class DateUtils {
|
|
|
// 返回年份差异,即年龄
|
|
|
return period.getYears();
|
|
|
}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 根据身份证的号码算出当前身份证持有者的年龄
|
|
|
+ *
|
|
|
+ * @param idCard 身份证号码
|
|
|
+ * @return 年龄
|
|
|
+ */
|
|
|
+ public int getAgeForIdCard(String idCard) {
|
|
|
+ try {
|
|
|
+ int age = 0;
|
|
|
+ if (idCard.isEmpty() || idCard.isBlank()) {
|
|
|
+ return age;
|
|
|
+ }
|
|
|
+
|
|
|
+ String birth = "";
|
|
|
+ if (idCard.length() == 18) {
|
|
|
+ birth = idCard.substring(6, 14);
|
|
|
+ } else if (idCard.length() == 15) {
|
|
|
+ birth = "19" + idCard.substring(6, 12);
|
|
|
+ }
|
|
|
+
|
|
|
+ int year = Integer.valueOf(birth.substring(0, 4));
|
|
|
+ int month = Integer.valueOf(birth.substring(4, 6));
|
|
|
+ int day = Integer.valueOf(birth.substring(6));
|
|
|
+ Calendar cal = Calendar.getInstance();
|
|
|
+ age = cal.get(Calendar.YEAR) - year;
|
|
|
+ //周岁计算
|
|
|
+ if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
|
|
|
+ age--;
|
|
|
+ }
|
|
|
+ return age;
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.getMessage();
|
|
|
+ }
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
}
|