(TS)根据身份证号码计算性别和年龄

// 记住变量用const定义,常量用let定义,不然类型会报错
const onCompute = () => {
    let identityNo = '511622200001011489'; // 身份证号码
    let sex = '';
    // 计算性别
    if (identityNo.substr(16, 1) % 2 === 1) {
      sex = '男';
    } else {
      sex = '女';
    }
    const birthYear = identityNo.substring(6, 10);
    const monthBirth = identityNo.substring(10, 12);
    const birthDay = identityNo.substring(12, 14);
    // 获取当前年月日
    const myDate = new Date();
    const nowMonth = myDate.getMonth() + 1;
    const nowDay = myDate.getDay();
    // 计算年龄
    let age = myDate.getFullYear() - birthYear ;
    if (nowMonth < monthBirth || (nowMonth === monthBirth && nowDay < birthDay )) {
      age -= 1;
    }
  console.log('性别------>',sex);
  console.log('年龄------>',age);
  };
微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?