常用的js

//根据选择的日期 计算出年龄
export const birthdayToAge = (strBirthday) => {
    var returnAge,
        strBirthdayArr = strBirthday.split("-"),
        birthYear = strBirthdayArr[0],
        birthMonth = strBirthdayArr[1],
        birthDay = strBirthdayArr[2],
        d = new Date(),
        nowYear = d.getFullYear(),
        nowMonth = d.getMonth() + 1,
        nowDay = d.getDate();
    if (nowYear == birthYear) {
        returnAge = 0; //同年 则为0周岁
    } else {
        var ageDiff = nowYear - birthYear; //年之差
        if (ageDiff > 0) {
            if (nowMonth == birthMonth) {
                var dayDiff = nowDay - birthDay; //日之差
                if (dayDiff < 0) {
                    returnAge = ageDiff - 1;
                } else {
                    returnAge = ageDiff;
                }
            } else {
                var monthDiff = nowMonth - birthMonth; //月之差
                if (monthDiff < 0) {
                    returnAge = ageDiff - 1;
                } else {
                    returnAge = ageDiff;
                }
            }
        } else {
            returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
        }
    }
    let resAge = ''
    resAge = returnAge;
    var NowYear = d.getFullYear();
    if (resAge > NowYear - 1) {
        resAge = "";
    }
    return resAge
}



// 将日期转换成以横杠连接的年月日
export const dateToConnect = (status) => {
    let res = status.getFullYear() + '-' + _addZero(status.getMonth() + 1) + '-' + _addZero(status.getDate())
    return res
}
 
// 根据身份证号 生成birthday sex age 

export function bornBirSexAge(idNum) {
    let form = {};
    form.birthday = idNum.substring(6, 10) +
        "-" +
        idNum.substring(10, 12) +
        "-" +
        idNum.substring(12, 14);
    form.sex = parseInt(idNum.substr(16, 1)) % 2 == 1 ? "0" : "1";
    form.age = birthdayToAge(form.birthday)
    return form;
}
原文地址:https://www.cnblogs.com/ylblogs/p/13256242.html