Android 中判斷年齡是否在16歲以下(含16歲)及其方法的封裝使用

weixin_34290000發表於2018-07-25

專案中有個需求:根據身份證號判斷做社保卡申領的人是否是16歲以下(含16歲)的未成年人,是的話,需要父母陪伴

我的實現思路:
就是通過身份證號碼先判斷出這個人是多少歲,然後在跟當前時間做對比,重要的一點是臨界時間的判斷,也就是剛好是16的差值,那就需要再通過判斷月份和日期來做判斷,是否符合條件
為了通用,我把方法封裝了一下,可以輸入年齡,然後判斷是否是在多少歲年齡一下,還可以設定是否包含當前年齡
核心程式碼如下:
1、獲取真實的年齡
   /**
     * 獲取真實的年齡
     *
     * @param idNum
     * @return
     */
    public static int getRealYear(String idNum) {

        Calendar cal = Calendar.getInstance();
        //當前年
        int currentYear = cal.get(Calendar.YEAR);
        //當前月
        int currentMonth = (cal.get(Calendar.MONTH)) + 1;
        //當前月的第幾天:即當前日
        int currentDay = cal.get(Calendar.DAY_OF_MONTH);


        int birthYear = 0;
        int birthMonth = 0;
        int birthDay = 0;
        int realYear = 0;

        if (!TextUtils.isEmpty(idNum)) {
            String birthDate = idNum.substring(6, 14);

            if (!TextUtils.isEmpty(birthDate) && birthDate.length() == 8) {
                birthYear = Integer.valueOf(birthDate.substring(0, 4));
                birthMonth = Integer.valueOf(birthDate.substring(4, 6));
                birthDay = Integer.valueOf(birthDate.substring(6, 8));
            }

            realYear = currentYear - birthYear;

            if (birthMonth > currentMonth) {
                realYear = realYear - 1;
            } else if (birthMonth == currentMonth) {
                if (birthDay > currentDay) {
                    realYear = realYear - 1;
                } else {
                    realYear = realYear;
                }
            } else {
                realYear = realYear;
            }
        }

        return realYear;
    }

2、判斷是否小於或者等於當前專案中規定的年齡

    /**
     * 判斷是否小於或者等於當前age的年齡
     *
     * @param age
     * @return
     */
    public static boolean isChildUnderTargetAge(String idNum, int age, boolean isIncludeAge) {
        int realYear = getRealYear(idNum);
        if (isIncludeAge) {
            if (realYear <= age) {
                return true;
            } else {
                return false;
            }
        } else {
            if (realYear < age) {
                return true;
            } else {
                return false;
            }
        }

    }
3、符合16歲以下(含16歲)

    /**
     * 判斷是否  是  > 2002年出生的     就是符合16歲以下(含16歲)
     *
     * @param birthDay
     * @return
     */
    public static boolean isChildUnder16(String birthDay) {
        return isChildUnderTargetAge(birthDay, 16, true);
    }
4、程式碼中呼叫
 boolean isChildUnder16 = IdcardUtils.isChildUnder16(mBean.sfzh);

相關文章