第一種(推薦使用):
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"));; }*/}