根据身份证号判断是否成年
1.1取出年月日和当前年月日进行比较
- 截取身份证相应的年,月,日(以下用生日年,生日月,生日天代替)
- 获取当前时间的年,月,日(以下用当前年,当前月,当前天代替)
- 如果当前年减去生日年 大于18 可以说明已经成年
- 如果当前年减去生日年 小于18 也可以说明未成年
- 如果当前年减去生日年 等于18,则需要判断生日是否已经过去
- 先判断生日月是否过去
- 如果当前月减去生日月 大于 0 可以说明已经成年
- 如果当前月减去生日月 小于 0 也可以说明未成年
- 如果当前月减去生日月 等于 0 则需要再判断生日天是否过去
- 如果当前天减去生日天 大于 0 可以说明已经成年
- 如果当前天减去生日天 小于 0 也可以说明未成年
public static void isAdultInId(String str){
int birthdayYear = Integer.parseInt(str.substring(6,10));
Calendar calendar = Calendar.getInstance();
int currentYear = calendar.get(Calendar.YEAR);
if(currentYear - birthdayYear == 18){
int birthdayMonth = Integer.parseInt(str.substring(10,12));
int currentMonth = calendar.get(Calendar.MONTH) + 1;
if(currentMonth - birthdayMonth == 0){
int birthdayDay = Integer.parseInt(str.substring(12,14));
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
if(currentDay - birthdayDay >= 0){
System.out.println("已经成年");
}else{
System.out.println("还未成年");
}
}else if(currentMonth - birthdayMonth > 0){
System.out.println("已经成年");
}else{
System.out.println("还未成年");
}
}else if(currentYear - birthdayYear > 18){
System.out.println("已经成年");
}else{
System.out.println("还未成年");
}
}
1.2取出年月日和当前年月日进行比较
- 直接使用当前年月日和出生年月日相减,大于等于180000,就是成年
- 例出生年月日为:20051025,当前年月日为 20231025 相减为180000,刚好成年
- 出生年月日为:20051026,当前年月日为 20231025 相减为179999,不会大于18000,就还未成年
public static void isAdultInId(String str){
int birthdayYearkMonthDay = Integer.parseInt(str.substring(6,14));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String currentYearMonthDayStr = sdf.format(new Date());
int currentYearMonthDay = Integer.parseInt(sdf.format(new Date()));
if(currentYearMonthDay - birthdayYearkMonthDay >= 180000){
System.out.println("已经成年");
}else{
System.out.println("还未成年");
}
}