package com.panzhihua.common.utlis; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * @program: springcloud_k8s_panzhihuazhihuishequ * @description: 年龄 * @author: huang.hongfa weixin hhf9596 qq 959656820 * @create: 2021-02-06 17:27 **/ public class IdCard { public static int IdNOToAge(String IdNO) { int leh = IdNO.length(); String dates = ""; int age = 0; if (leh == 18) { dates = IdNO.substring(6, 10); SimpleDateFormat df = new SimpleDateFormat("yyyy"); String year = df.format(new Date()); age = Integer.parseInt(year) - Integer.parseInt(dates); } else { System.out.println("出错!身份证长度不是18位!"); } return age; } public static Date birthDay(String Id) { /*从身份证截取生日信息 * author:huangjy 2016-07-15 Date转换成String,只需将parse方法换成format方法 * */ String year = Id.substring(6, 10);// 调用substring方法返回相关字段,注意索引从0开始 String month = Id.substring(10, 12); String day = Id.substring(12, 14); String birthday = year + "-" + month + "-" + day; DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");// 定义一个时间转换格式“年-月-日” Date date = null; try { // 捕获类型转换(解析)异常 date = fmt.parse(birthday); } catch (ParseException e) { e.printStackTrace(); } return date; } public static Integer sex(String id) { Integer sex; if (Integer.parseInt(id.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别 sex = 2; } else { sex = 1; } return sex; } public static void main(String[] args) { System.out.println(birthDay("120000197802150561")); System.out.println(birthDay("32000019951110538X")); } }