记得上下班打卡 | git大法好,push需谨慎

Commit 0b5a0569 authored by 张国柄's avatar 张国柄

~年龄校验精确到天;

parent 6f4fdb7f
...@@ -75,7 +75,7 @@ public class IDCardUtil { ...@@ -75,7 +75,7 @@ public class IDCardUtil {
} }
/** /**
* 根据身份证号获取年龄 * 根据身份证号获取年龄,精确到天
* *
* @param idNo * @param idNo
* @return int * @return int
...@@ -84,31 +84,51 @@ public class IDCardUtil { ...@@ -84,31 +84,51 @@ public class IDCardUtil {
int age = 0; int age = 0;
if (StringUtils.isNotBlank(idNo)) { if (StringUtils.isNotBlank(idNo)) {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
int nowYear = now.getYear(), nowMonth = now.getMonthValue();// 当前年份、月份 int nowYear = now.getYear(), nowMonth = now.getMonthValue(), nowDay = now.getDayOfMonth();// 当前年份、月份
String uYear, uMonth;// 身份证年份、月份 String uYear, uMonth, uDay;// 身份证年份、月份、天
switch (idNo.length()) { switch (idNo.length()) {
case FIFTEEN_ID_CARD: case FIFTEEN_ID_CARD:
// 身份证上的年份(15位身份证为1980年前的) // 身份证上的年份(15位身份证为1980年前的)
uYear = "19" + idNo.substring(6, 8); uYear = "19" + idNo.substring(6, 8);
// 身份证上的月份 // 身份证上的月份
uMonth = idNo.substring(8, 10); uMonth = idNo.substring(8, 10);
// 身份证上的天
uDay = idNo.substring(10, 12);
break; break;
case EIGHTEEN_ID_CARD: case EIGHTEEN_ID_CARD:
// 身份证上的年份 // 身份证上的年份
uYear = idNo.substring(6).substring(0, 4); uYear = idNo.substring(6).substring(0, 4);
// 身份证上的月份 // 身份证上的月份
uMonth = idNo.substring(10).substring(0, 2); uMonth = idNo.substring(10).substring(0, 2);
// 身份证上的天
uDay = idNo.substring(12).substring(0, 2);
break; break;
default: default:
return 0; return 0;
} }
if (nowMonth >= Integer.parseInt(uMonth)) {// 当前月份大于用户出身的月份表示已过生日 int diff = nowYear - Integer.parseInt(uYear);
age = nowYear - Integer.parseInt(uYear) + 1; if (diff == 18) {
int uMonthNum = Integer.parseInt(uMonth);
if (nowMonth > uMonthNum) {// 当前月份>用户出生月份,已过生日
age = diff;
} else if (nowMonth < uMonthNum) {// 当前月份<用户出生月份,未过生日
age = diff - 1;
} else if (nowDay >= Integer.parseInt(uDay)) {// 当前月份==用户出生月份 && 当前天>用户出身天,已过生日||当天生日
age = diff;
} else {// 当前月份==用户出生月份 && 当前天<=用户出身天,未过生日
age = diff - 1;
}
} else { } else {
age = nowYear - Integer.parseInt(uYear); age = diff;
} }
// if (nowMonth >= Integer.parseInt(uMonth)) {// 当前月份大于用户出身的月份表示已过生日
// age = nowYear - Integer.parseInt(uYear) + 1;
// } else {
// age = nowYear - Integer.parseInt(uYear);
// }
} }
return age; return age;
} }
...@@ -146,8 +166,4 @@ public class IDCardUtil { ...@@ -146,8 +166,4 @@ public class IDCardUtil {
// } // }
// return birthday; // return birthday;
// } // }
public static void main(String[] args) {
System.out.println(IDCardUtil.getAge("141181199209160192"));
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment