The following code is to share with you the method of java calculating age based on ID cards. The specific code is as follows:
birthDate = idCard.substring(6,10)+"-"+idCard.substring(10,12)+"-"+idCard.substring(12,14)public static int getAgefromBirthTime(String birthTimeString){ // First intercept the year, month, and day in the string String strs[] = birthTimeString.trim().split("-"); int selectYear = Integer.parseInt(strs[0]); int selectMonth = Integer.parseInt(strs[1]); int selectDay = Integer.parseInt(strs[2]); // Get the year, month and day of the current time Calendar cal = Calendar.getInstance(); int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH) + 1; int dayNow = cal.get(Calendar.DATE); // Subtract the birthday year, month and day with the current year, month and day int yearMinus = yearNow - selectYear; int monthMinus = monthNow - selectMonth; int dayMinus = dayNow - selectDay; int age = yearMinus; if (yearMinus < 0) {// Select the future year age = 0; } else if (yearMinus == 0) {// The same year is either 1 or 0 if (monthMinus < 0) {// Select the future month age = 0; } else if (monthMinus == 0) {// If (dayMinus < 0) {// Select the future date age = 0; } else if (dayMinus >= 0) { age = 1; } } else if (monthMinus > 0) { age = 1; } } else if (yearMinus > 0) { age = 1; } } else if (yearMinus > 0) { if (monthMinus < 0) {// Current month>Birthday month} else if (monthMinus == 0) {// For the same month, calculate the age based on the date if (dayMinus < 0) { } else if (dayMinus >= 0) { age = age + 1; } } else if (monthMinus > 0) { age = age + 1; } } return age;}Let's take a look at the age obtained by java based on the date of birth
public static int getAge(Date birthDay) throws Exception { Calendar cal = Calendar.getInstance(); if (cal.before(birthDay)) { throw new IllegalArgumentException( "The birthday is before Now.It's unbelievable!"); } int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH); int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birthDay); int yearBirth = cal.get(Calendar.YEAR); int monthBirth = cal.get(Calendar.MONTH); int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { if (dayOfMonthNow < dayOfMonthBirth) age--; }else{ age--; } } System.out.println("age:"+age); return age; }Summarize
The above is the JAVA introduced by the editor to you by calculating age based on your ID card. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!