通过身份证号取得年龄,性别

import java.util.Calendar;

public class IdCardUtil {

    public static Integer getAge(String idCard){
        //生日
        Integer year = BeanUtil.toInteger(idCard.substring(6, 10));
        Integer month = BeanUtil.toInteger(idCard.substring(10,12));
        Integer date = BeanUtil.toInteger(idCard.substring(12, 14));
        
        //当前年月日
        Calendar now = Calendar.getInstance();
        Integer nowYear = now.get(Calendar.YEAR);
        Integer nowMonth = now.get(Calendar.MONTH) + 1;
        Integer nowDate = now.get(Calendar.DATE);
        
        //判断取得年龄
        Integer age = nowYear - year;
        if(nowMonth < month){
            age = age -1;
        }else if(nowMonth == month){
            if(nowDate < date){
                age = age -1;
            }
        }
        return age;
    }
    /**
     * 
     * @param idCard
     * @return  1为男性,2为女性
     */
    public static Integer getSex(String idCard){
        Integer sex=BeanUtil.toInteger(idCard.substring((idCard.length()-2), (idCard.length()-1)));
        if(sex%2==0){
            return 2;
        }
        return 1;
    }
    
    public static void main(String args[]){
        System.out.println(getSex("412726199212123398"));
    }
}

你可能感兴趣的:(通过身份证号取得年龄,性别)