二话不说,直接上代码。

package hope.identitycodecheck.demo;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author hp
*
* */
public class IdentityCodeUtil {
/**
* 身份证号校验 (支持18位)
*
* */
public static boolean checkIdentityCode(String identityCode) {
if (!identityCode.matches("\\d{17}(\\d|x|X)$")) {
return false;
}
Date d = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMdd");
int year = Integer.parseInt(df.format(d));
if (Integer.parseInt(identityCode.substring(6, 10)) < 1900 || Integer.parseInt(identityCode.substring(6, 10)) > year) {// 7-10位是出生年份,范围应该在1900-当前年份之间
return false;
}
if (Integer.parseInt(identityCode.substring(10, 12)) < 1 || Integer.parseInt(identityCode.substring(10, 12)) > 12) {// 11-12位代表出生月份,范围应该在01-12之间
return false;
}
if (Integer.parseInt(identityCode.substring(12, 14)) < 1 || Integer.parseInt(identityCode.substring(12, 14)) > 31) {// 13-14位是出生日期,范围应该在01-31之间
return false;
}
// 校验第18位
// S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和
// Ai:表示第i位置上的身份证号码数字值
// Wi:表示第i位置上的加权因子
// Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
String[] tempA = identityCode.split("|");
int[] a = new int[18];
for (int i = 0; i < tempA.length - 2; i++) {
a[i] = Integer.parseInt(tempA[i + 1]);
}
int[] w = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 加权因子
int sum = 0;
for (int i = 0; i < 17; i++) {
sum = sum + a[i] * w[i];
}
// Y = mod(S, 11)
// 通过模得到对应的校验码
// Y: 0 1 2 3 4 5 6 7 8 9 10
// 校验码: 1 0 X 9 8 7 6 5 4 3 2
String[] v = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" }; // 校验码
int y = sum % 11;
if (!v[y].equalsIgnoreCase(identityCode.substring(17))) {// 第18位校验码错误
return false;
}
return true;
} public static void main(String[] args) {
System.out.println(checkIdentityCode("110110198001019719"));
}
}

最新文章

  1. Interleaving String
  2. ubuntu samba 服务器设置
  3. LINQ to SQL语句(4)之Join
  4. 【Android】Fragment真正意义上的onResume和onPause
  5. 使用gdb调试多线程程序总结
  6. linux解压cpio.gz类型文件
  7. poj2325
  8. Unix/Linux环境C编程入门教程(28) 日期时间那些事儿
  9. 【leetcode系列】Valid Parentheses
  10. Linux系统中调用短信猫发送短信(笔记)
  11. js实现简单的轮播效果
  12. IO流系列一:输入输出流的转换
  13. SpringCloud系列——SSO 单点登录
  14. day16 Python 内置函数 大体演示想看就看,会用就行
  15. corosync+pacemaker的crmsh的常用指令介绍
  16. [LeetCode] 643. Maximum Average Subarray I_Easy tag: Dynamic Programming(Sliding windows)
  17. 《算法》第四章部分程序 part 9
  18. hadoop2相对hadoop1有非常重大的改进
  19. Broker流量均衡 prefer reassign
  20. 20155308 2016-2017-2《Java程序设计》课堂实践项目

热门文章

  1. fastjson 应用
  2. chisel(安装)
  3. centos7部署harbor
  4. mac安装mysql及workbench
  5. mysql的jdbc.url携带allowMultiQueries=true参数的作用及其原理
  6. python__基础 : 类的继承,调用父类的属性和方法
  7. pytorch中如何使用预训练词向量
  8. 霍夫直线检测 opencv
  9. python基础之入门基础
  10. 2 实现第一个Django网站 博客