Java实现身份证获取年龄

通过身份证获取年龄

/**
     * 根据身份证号获取年龄
     * @param certId
     * @return
     */
    public static String getAgeByCertId(String certId) {
        String birthday = "";
        if (certId.length() == 18) {
           birthday = certId.substring(6, 10) + "/"
                   + certId.substring(10, 12) + "/"
                   + certId.substring(12, 14);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");  
        Date now = new Date();
        Date birth = new Date();
        try {
            birth = sdf.parse(birthday);
        } catch (ParseException e) {
        }
        long intervalMilli = now.getTime() - birth.getTime();
        int age = (int) (intervalMilli/(24 * 60 * 60 * 1000))/365;
        System.out.println(age);
        return age +"";
    }

你可能感兴趣的:(java)