通过身份证号计算出生日期、年龄, 脱敏
根据身份证号获取出生日期
// 根据身份证号获取出生日期
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;
};