通过身份证号获取年龄

@RequestMapping("getAge")
    public Integer getAge(String idCard) {
        int selectYear = Integer.parseInt(idCard.substring(6, 10));
        int selectMonth = Integer.parseInt(idCard.substring(10, 12));
        int selectDay = Integer.parseInt(idCard.substring(12, 14));
        // 得到当前时间的年、月、日
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);
        // 用当前年月日减去生日年月日
        int yearMinus = yearNow - selectYear;
        int monthMinus = monthNow - selectMonth;
        int dayMinus = dayNow - selectDay;
        //年龄
        int age = yearMinus;
        if (yearMinus > 0) {
            if (monthMinus <= 0 && dayMinus < 0) {
                age = age - 1;
            }
        } else {
            age = 0;
        }
        return age;
    }
上一篇:Java基础(7)


下一篇:数据结构基础(1.2) -- 多数元素