最近项目上有一个需要根据身份证获取老人周岁的功能,本以为当前年直接减去身份证的出生年就好了。结果测试提了过了生日就是+1岁,没过生日才是正确的。于是呼,哗哗的改代码。下面分别贴出java计算和js计算:
java计算
public Integer handleIdentityAge(String identity,Integer year,Integer month,Integer day){
if(identity.length()<10){
return 0;
}
Integer selectYear=Integer.valueOf(identity.substring(6,10));
Integer selectMonth=Integer.valueOf(identity.substring(10,12));
Integer selectDay = Integer.valueOf(identity.substring(12, 14));
Integer yearMinus = year - selectYear;
Integer monthMinus = month - selectMonth;
Integer dayMinus = day - selectDay;
Integer age = yearMinus;
if(yearMinus<0){
age = 0;
}else if (yearMinus == 0) {
age = 0;
} else if (yearMinus > 0) {
if (monthMinus == 0) {
if (dayMinus < 0) {
age = age - 1;
}
} else if (monthMinus > 0) {
age = age + 1;
}
}
return age;
}
js计算
function calculatingAge (identity) {
if(identity.length < 10) {
return "";
}
debugger
var birthYear = identity.substr(6, 4);
var birthMonth = identity.substr(10, 2);
var birthDay = identity.substr(12, 2);
var d = new Date();
var nowYear = d.getFullYear();
var nowMonth = d.getMonth() + 1;
var nowDay = d.getDate();
let returnAge = 0;
let result = 0;
//1997-11-16
if(nowYear == birthYear) {
returnAge = 0; //同年 则为0岁
} else {
var ageDiff = nowYear - birthYear; //年之差
if(ageDiff > 0) {
if(nowMonth == birthMonth) {
var dayDiff = nowDay - birthDay; //日之差
if(dayDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
} else {
var monthDiff = nowMonth - birthMonth; //月之差
if(monthDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
}
} else {
returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge;
}
以上两种方式都是根据身份证号计算周岁,避免重复造轮子,可以直接复制使用。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/143391.html