js根据身份证获取性别、年龄、出生日期及根据出生日期获取年龄

js根据身份证获取性别、年龄、出生日期及根据出生日期获取年龄

//{"sexCode":"2","sexLabel":"女","birthDate":"1995-01-05","age":28}
    console.log("身份证信息"+JSON
        .stringify(getIdCardInfo("340521199501055621")))
/**
 * 读取身份证信息
 * @param idCard
 * @returns {*}
 */
function getIdCardInfo(idCard) {
    var idCardObj = {};
    //获取用户身份证号码
    //获取性别
    if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
        idCardObj.sexCode = '1' //男
    } else {
        idCardObj.sexCode = '2' //女
    }
    //获取出生年月日
    var yearBirth = idCard.substring(6, 10);
    var monthBirth = idCard.substring(10, 12);
    var dayBirth = idCard.substring(12, 14);
    var birthDate = yearBirth + "-" + monthBirth + "-" + dayBirth;
    //获取当前年月日并计算年龄
    var myDate = new Date();
    var monthNow = myDate.getMonth() + 1;
    var dayNow = myDate.getDay();
    var age = myDate.getFullYear() - yearBirth;
    if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
        age--;
    }
    //得到年龄
    idCardObj.birthDate = birthDate;
    idCardObj.age = age;
    //返回性别和年龄
    return idCardObj;
}

你可能感兴趣的:(Js,javascript,前端,开发语言)