java实现根据身份证计算年龄的两种方式

时间:2024-03-06 13:34:12
第一种(推荐使用):

import org.apache.hadoop.hive.ql.exec.UDF;

import java.util.Calendar;

public class GetAge extends UDF {

public String evaluate(String sfzjh){

if(sfzjh == null || "".equals(sfzjh) ){
return "身份证件号有误,无法计算年龄";
}

if (sfzjh.length() != 15 && sfzjh.length() != 18){
return "身份证件号有误,无法计算年龄";
}

String age="身份证件号有误,无法计算年龄";

CheckSFZ sf = new CheckSFZ(); // 调用校验身份证的函数,若身份证完全正确,此处可以不需要
sfzjh = sf.evaluate(sfzjh);

if(sfzjh != "身份证件号有误"){

Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH)+1;
int dayNow = cal.get(Calendar.DATE);

int year = Integer.valueOf(sfzjh.substring(6, 10));
int month = Integer.valueOf(sfzjh.substring(10,12));
int day = Integer.valueOf(sfzjh.substring(12,14));

if ((month < monthNow) || (month == monthNow && day<= dayNow) ){
age = String.valueOf(yearNow - year);
}else {
age = String.valueOf(yearNow - year-1);
}

}

return age;
}

/*public static void main(String[] args) {
GetAge ga = new GetAge();
String sfzjh = "360731199701024351";
int year = Integer.valueOf(sfzjh.substring(6, 10));
int month = Integer.valueOf(sfzjh.substring(10,12));
int day = Integer.valueOf(sfzjh.substring(12,14));
System.out.println(year + ""+month+""+day);
System.out.println(ga.evaluate("360731970909435"));

}*/

}


第二种(不推荐使用,有系统bug):

import org.apache.hadoop.hive.ql.exec.UDF;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class GetAge1 extends UDF {

public String evaluate(String sfzjh) throws ParseException {

if(sfzjh == null || "".equals(sfzjh) ){
return "身份证件号有误,无法计算年龄";
}

if (sfzjh.length() != 15 && sfzjh.length() != 18){
return "身份证件号有误,无法计算年龄";
}

String age="身份证件号有误,无法计算年龄";

CheckSFZ sf = new CheckSFZ(); // 调用校验身份证的函数,若身份证完全正确,此处可以不需要
sfzjh = sf.evaluate(sfzjh);
if(sfzjh != "身份证件号有误"){
Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH)+1;
int dayNow = cal.get(Calendar.DATE);
SimpleDateFormat format = new SimpleDateFormat("yyyymmdd");
long millNow = format.parse(yearNow+""+(monthNow < 10 ? 0+""+monthNow :monthNow)+""+(dayNow < 10 ? 0+""+dayNow:dayNow)).getTime();
long mill = format.parse(sfzjh.substring(6,14)).getTime(); //将出生日期转化为毫秒值
long ag = (millNow - mill)/(1000*60*60)/(365*24);
//age = String.valueOf(Math.floor(ag));
age = String.valueOf(ag);
}

return age;
}

/*public static void main(String[] args) throws ParseException {

GetAge1 ag = new GetAge1();
System.out.println(ag.evaluate("360731980102400"));;

}*/

}








相关文章