java根据身份证号获取周岁年龄
public static void main ( String[ ] args) {
System. out. println ( getCurrectAge ( DateUtils. dateTime ( "yyyy-MM-dd" , convertBirthDate ( "311111200307281111" ) ) ) ) ;
}
public static final Date dateTime ( final String format, final String ts) {
try {
return new SimpleDateFormat ( format) . parse ( ts) ;
} catch ( ParseException e) {
throw new RuntimeException ( e) ;
}
}
public static String convertBirthDate ( String str) {
String year = str. substring ( 6 , 10 ) ;
String month = str. substring ( 10 , 12 ) ;
String day = str. substring ( 12 , 14 ) ;
String birthday = year + "-" + month + "-" + day;
return birthday;
}
public static int getCurrectAge ( Date birthday) {
Calendar curr = Calendar. getInstance ( ) ;
Calendar born = Calendar. getInstance ( ) ;
born. setTime ( birthday) ;
int age = curr. get ( Calendar. YEAR) - born. get ( Calendar. YEAR) ;
if ( age <= 0 ) {
return 0 ;
}
int currMonth = curr. get ( Calendar. MONTH) ;
int currDay = curr. get ( Calendar. DAY_OF_MONTH) ;
int bornMonth = born. get ( Calendar. MONTH) ;
int bornDay = born. get ( Calendar. DAY_OF_MONTH) ;
if ( ( currMonth < bornMonth) || ( currMonth == bornMonth && currDay <= bornDay) ) {
age-- ;
}
return age < 0 ? 0 : age;
}