通过身份证号计算出生日期、年龄, 脱敏

通过身份证号计算出生日期、年龄, 脱敏

根据身份证号获取出生日期

// 根据身份证号获取出生日期
export const getBirthdayFromIdCard = (idCard) => {
  let birthday = '';
  if (idCard != null && idCard !== '') {
    if (idCard.length === 15) {
      birthday = '19'.concat(idCard.substr(6, 6));
    } else if (idCard.length === 18) {
      birthday = idCard.substr(6, 8);
    }
    birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');
  }

  return birthday;
};

根据出生日期计算年龄

// 根据出生日期计算年龄
export const getAge = (birthday: string, createDate: Date = new Date()) => {
  if (birthday) {
    if (birthday.length < 10) {
      birthday.concat(' 00:00:00');
    }
    let age;
    const birthDate = new Date(birthday);
    const birthdayYear = birthDate.getFullYear();
    const birthdayMonth = birthDate.getMonth() + 1;
    const birthdayDay = birthDate.getDate();
    const today = createDate;
    const nowYear = today.getFullYear();
    const nowMonth = today.getMonth() + 1;
    const nowDay = today.getDate();
    if (nowYear === birthdayYear) {
      age = 0; // 同年 则为0岁
    } else {
      const ageDiff = nowYear - birthdayYear; // 年之差
      if (ageDiff > 0) {
        if (nowMonth === birthdayMonth) {
          const dayDiff = nowDay - birthdayDay; // 日之差
          if (dayDiff < 0) {
            age = ageDiff - 1;
          } else {
            age = ageDiff;
          }
        } else {
          const monthDiff = nowMonth - birthdayMonth; // 月之差
          if (monthDiff < 0) {
            age = ageDiff - 1;
          } else {
            age = ageDiff;
          }
        }
      } else {
        age = '未知'; // 返回-1 表示出生日期输入错误 晚于今天
      }
    }
    return age; // 返回周岁年龄
  }
  return '未知';
};

身份证脱敏

// 身份证脱敏
export const getCardId = (value: any) => {
  if (value && value.length >= 18) {
    return `${value.substr(0, 10)}****${value.substr(value.length - 4, 4)}`;
  }
  if (!value) {
    return '-';
  }
  return value;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值