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

声明:网上目前有很多采用JS写的,随便一搜就能搜到,这里我用在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);
  };
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值