记录身份证工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import java.time.LocalDateTime;
import static java.lang.Integer.parseInt;
public class IdentityCardUtils {
/**
* 获取年
*
* @param idNumber
* @return
*/
public static int getYear(String idNumber) {
if (idNumber.length() == 15) {
return parseInt("19" + idNumber.substring(6, 8));
}
return parseInt(idNumber.substring(6, 10));
}
/**
* 获取月
*
* @param idNumber
* @return
*/
public static int getMonth(String idNumber) {
if (idNumber.length() == 15) {
return parseInt(idNumber.substring(8, 10));
}
return parseInt(idNumber.substring(10, 12));
}
/**
* 获取日
*
* @param idNumber
* @return
*/
public static int getDay(String idNumber) {
if (idNumber.length() == 15) {
return parseInt(idNumber.substring(10, 12));
}
return parseInt(idNumber.substring(12, 14));
}
/**
* 获取出生年月日
*
* @param idNumber
* @return
*/
public static String getYearMonthDay(String idNumber) {
if (idNumber.length() == 15) {
return "19" + idNumber.substring(6, 12);
}
return idNumber.substring(6, 14);
}
/**
* 获取指定格式化之后的出生年月日
*
* @param idNumber
* @return
*/
public static String getFormatYMD(String idNumber, String format) {
int year = IdentityCardUtils.getYear(idNumber);
int month = IdentityCardUtils.getMonth(idNumber);
int day = IdentityCardUtils.getDay(idNumber);
return new StringBuffer(String.valueOf(year)).append(format).append(month).append(format).append(day).toString();
}
/**
* 获取性别
*
* @param idNumber 1:男 0:女
* @return
*/
public static int getSex(String idNumber) {
String val = null;
if (idNumber.length() == 15) {
val = idNumber.substring(14, 15);
} else if (idNumber.length() == 18) {
val = idNumber.substring(16, 17);
}
assert val != null;
if (Integer.parseInt(val) % 2 == 0) {
return 0;
} else {
return 1;
}
}
public static String getSexString(String idNumber) {
return getSex(idNumber) == 0 ? "女" : "男";
}
/**
* 获取年龄
*
* @param idNumber
* @return
*/
public static int getAge(String idNumber) {
int currentYear = LocalDateTime.now().getYear();
int age = currentYear - getYear(idNumber);
int month = getMonth(idNumber);
int currentMonth = LocalDateTime.now().getMonthValue();
if (month > currentMonth) {
--age;
}
return age;
}
}