IdcardUtil

Origin

In daily development, our validation of ID cards is mainly based on regular methods (number of digits, numeric range, etc.). However, Chinese ID cards, especially the 18-digit ones, have strict regulations for each digit, and the last digit is a checksum. In practical applications, the validation of ID cards should be strict to comply with these regulations. Therefore, IdcardUtil was born.

IdcardUtil has been added to the Hutool tool family since version 3.0.4. Please upgrade to version 3.0.4 or above to use it.

Introduction

IdcardUtil now supports 15-digit and 18-digit ID cards in mainland China, and 10-digit ID cards in Hong Kong, Macao, and Taiwan.

The main methods in the tool include:

  1. isValidCard to validate the legitimacy of the ID card
  2. convert15To18 to convert a 15-digit ID card to a 18-digit one
  3. getBirthByIdCard to get the birthday
  4. getAgeByIdCard to get the age
  5. getYearByIdCard to get the birth year
  6. getMonthByIdCard to get the birth month
  7. getDayByIdCard to get the birth day
  8. getGenderByIdCard to get the gender
  9. getProvinceByIdCard to get the province

Usage

String ID_18 = "321083197812162119";
String ID_15 = "150102880730303";

// Whether it is valid
boolean valid = IdcardUtil.isValidCard(ID_18); // true
boolean valid15 = IdcardUtil.isValidCard(ID_15); // true

// Converting from 15 digits to 18 digits
String convert15To18 = IdcardUtil.convert15To18(ID_15); // "150102198807303035"
Assert.assertEquals(convert15To18, "150102198807303035");

// Age
DateTime date = DateUtil.parse("2017-04-10");
    
int age = IdcardUtil.getAgeByIdCard(ID_18, date); // 38
Assert.assertEquals(age, 38);

int age2 = IdcardUtil.getAgeByIdCard(ID_15, date); // 28
Assert.assertEquals(age2, 28);

// Birthday
String birth = IdcardUtil.getBirthByIdCard(ID_18); // "19781216"
Assert.assertEquals(birth, "19781216");

String birth2 = IdcardUtil.getBirthByIdCard(ID_15); // "19880730"
Assert.assertEquals(birth2, "19880730");

// Province
String province = IdcardUtil.getProvinceByIdCard(ID_18); // "江苏"
Assert.assertEquals(province, "江苏");

String province2 = IdcardUtil.getProvinceByIdCard(ID_15); // "内蒙古"
Assert.assertEquals(province2, "内蒙古");

Declaration The two ID card numbers above are randomly fabricated and are purely coincidental if any similarity occurs.