介紹
根據身份證號計算年齡
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;}}