介绍
根据身份证号计算年龄
Java代码
/*** 根据身份证号计算年龄* @param birthDateStr* @return*/public static int calculateAge(String birthDateStr) {try {birthDateStr=birthDateStr.substring(6,6+8);// 定义日期格式SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");// 将字符串类型的出生日期转换为 Date 对象Date birthDate = sdf.parse(birthDateStr);// 获取当前的日期和时间Calendar now = Calendar.getInstance();// 获取当前年份int currentYear = now.get(Calendar.YEAR);// 获取当前月份int currentMonth = now.get(Calendar.MONTH) + 1;// 获取当前日期int currentDay = now.get(Calendar.DAY_OF_MONTH);// 创建一个 Calendar 对象来表示出生日期Calendar birthCalendar = Calendar.getInstance();birthCalendar.setTime(birthDate);// 获取出生年份int birthYear = birthCalendar.get(Calendar.YEAR);// 获取出生月份int birthMonth = birthCalendar.get(Calendar.MONTH) + 1;// 获取出生日期int birthDay = birthCalendar.get(Calendar.DAY_OF_MONTH);// 先计算年份差作为初始年龄int age = currentYear - birthYear;// 如果当前月份小于出生月份,说明还未到生日,年龄减 1if (currentMonth < birthMonth) {age--;} else if (currentMonth == birthMonth) {// 如果当前月份等于出生月份,再比较日期if (currentDay < birthDay) {// 如果当前日期小于出生日期,说明还未到生日,年龄减 1age--;}}return age;} catch (ParseException e) {// 处理日期解析异常,打印异常信息并返回 -1 表示错误e.printStackTrace();return -1;}}