- 日々の開発で使用するツールクラスの中には、ドキュメントクラスの処理を使用する必要があるものがあります。
@Slf4j
public class IdCardNoUtils {
private static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
/**
*18ビット単位のID番号: 17桁目は性別を表し、奇数は男性、偶数は女性である。
* @param idCardNo
* @return
*/
public static String getSex(String idCardNo) {
if (idCardNo == null || idCardNo.length() != 18) {
return "";
}
char c = idCardNo.charAt(16);
int sex = Integer.valueOf(c);
return sex % 2 == 0 ? " : " ;
}
/**
*18ビット単位のID番号: ビット7-14はyyyyMMddを表す。
* @param idCardNo
* @return
*/
public static Date getBirthday(String idCardNo) {
if (idCardNo == null || idCardNo.length() != 18) {
throw new BusinessException("IDフォーマットが間違っている!");
}
String birthdayStr = idCardNo.substring(6, 14);
Date birthday = null;
try {
birthday = formatter.parse(birthdayStr);
} catch (ParseException e) {
log.warn("日付フォーマットの変換エラー! birthday:" + birthday, e);
}
return birthday;
}
/**
*18ビット単位のID番号: ビット7-14はyyyyMMddを表し、年齢を計算するのに使用できる。
* @param idCardNo
* @return
*/
public static int getAge(String idCardNo) {
if (idCardNo == null || idCardNo.length() != 18) {
return -1;
}
String birthday = idCardNo.substring(6, 14);
Date birthdayDate = null;
try {
birthdayDate = formatter.parse(birthday);
} catch (ParseException e) {
log.warn("日付フォーマットの変換エラー! birthday:" + birthday, e);
}
return getAgeByDate(birthdayDate);
}
/**
* 年齢を1日単位で計算する
* @param birthday
* @return
*/
private static int getAgeByDate(Date birthday) {
Calendar calendar = Calendar.getInstance();
if (calendar.getTimeInMillis() - birthday.getTime() < 0L) {
return -1;
}
//現在の年、月、日
int yearNow = calendar.get(Calendar.YEAR);
int monthNow = calendar.get(Calendar.MONTH);
int dayNow = calendar.get(Calendar.DAY_OF_MONTH);
//生年月日
calendar.setTime(birthday);
int yearBirthday = calendar.get(Calendar.YEAR);
int monthBirthday = calendar.get(Calendar.MONTH);
int dayBirthday = calendar.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirthday;
//月または日は完全ではない
if (monthNow < monthBirthday || (monthNow == monthBirthday && dayNow < dayBirthday)) {
age = age - 1;
}
return age;
}