有个项目需要对接第三方,会定期返回用户的信息。
但里面缺少性别和年龄,按说这个不算啥。
架不住公司有要求,必须保证数据完整。
做过乙方的都懂,有时候让甲方改点东西难如登天。
下决心自己搞,不算太难的事(无奈╮(╯▽╰)╭)。
这样做能行吗?
行,一定行。
思路就是用身份证号,去计算用户的性别和年龄。
年龄需要注意一下,最好是返回给前端的时候动态计算(也可以缓存起来动态算,或者让前台自己算),这里只是展示结果。
Java实现:
/**
* 根据身份证号计算年龄和性别
*
*
* @param idCard 身份证号
* @return 对象
*/
public Result calculateAgeGender(String idCard) {
if (idCard == null || (idCard.length() != 15 && idCard.length() != 18)) {
return null;
}
String birthDateStr;
int genderCode;
if (idCard.length() == 15) {
birthDateStr = "19" + idCard.substring(6, 12);
genderCode = Integer.parseInt(idCard.substring(14, 15));
} else {
birthDateStr = idCard.substring(6, 14);
genderCode = Integer.parseInt(idCard.substring(16, 17));
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
LocalDate currentDate = LocalDate.now();
Period period = Period.between(birthDate, currentDate);
String gender = genderCode % 2 == 0 ? "女" : "男";
return new Result(period.getYears(), gender);
}
// 返回性别和年龄.
public class Result {
private int age;
private String gender;
// get..
// set..
}
如果是前端自己计算?别急,也准备好了:
// 使用原生js.
function calculateAgeGender(idCard) {
if (!idCard || (idCard.length !== 15 && idCard.length !== 18)) {
return null;
}
let birthDateStr;
let genderCode;
if (idCard.length === 15) {
birthDateStr = "19" + idCard.slice(6, 12);
genderCode = parseInt(idCard.charAt(14), 10);
} else {
birthDateStr = idCard.slice(6, 14);
genderCode = parseInt(idCard.charAt(16), 10);
}
const birthDate = new Date(`${birthDateStr.slice(0, 4)}-${birthDateStr.slice(4, 6)}-${birthDateStr.slice(6, 8)}`);
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
const gender = genderCode % 2 === 0 ? '女' : '男';
return { age, gender };
}
如果你用了dayjs,那就太好了,下面是dayjs的版本:
const dayjs = require('dayjs');
function calculateAgeGender(idCard) {
if (!idCard || (idCard.length !== 15 && idCard.length !== 18)) {
return null;
}
let birthDateStr;
let genderCode;
if (idCard.length === 15) {
birthDateStr = "19" + idCard.slice(6, 12);
genderCode = parseInt(idCard.charAt(14), 10);
} else {
birthDateStr = idCard.slice(6, 14);
genderCode = parseInt(idCard.charAt(16), 10);
}
const birthDate = dayjs(birthDateStr, 'YYYYMMDD');
const today = dayjs();
const age = today.diff(birthDate, 'year');
const gender = genderCode % 2 === 0 ? '女' : '男';
return { age, gender };
}
是不是相对来说,比较简单?