Java 通过身份证获取生日、性别、年龄
package com.taiping.ecms.car.utils; import java.util.Calendar; import java.util.Date; /** * 字符串相关工具类 * @author Alex * */ public class StringUtils { /** * 格式化字符串第一个字符为大写 * @param field * @return */ public static String upperFirstString(String field){ if(field.length() <= 0 || field == null){ return field; } String firstLetter = field.substring(0, 1).toUpperCase(); String formatString = firstLetter + field.substring(1); return formatString; } /** * 功能:在判定已经是正确的身份证号码之后,查找出此人性别 * @param idCard-身份证号码 * @return 1-男或者 2-女 */ public static String getSex(String idCard) { String sex = ""; if (idCard.length() == 15) { sex = idCard.substring(idCard.length() - 3, idCard.length()); } else { sex = idCard.substring(idCard.length() - 4, idCard.length() - 1); } int sexNum = Integer.parseInt(sex) % 2; if (sexNum == 0) { return "2"; } return "1"; } /** * 根据出生日期获取年龄 * @param birthDay * @return * @throws Exception */ public static int getAge(Date birthDay) throws Exception { Calendar cal = Calendar.getInstance(); if (cal.before(birthDay)) { throw new IllegalArgumentException( "The birthDay is before Now.It's unbelievable!"); } int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH); int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birthDay); int yearBirth = cal.get(Calendar.YEAR); int monthBirth = cal.get(Calendar.MONTH); int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { if (dayOfMonthNow < dayOfMonthBirth) age--; }else{ age--; } } return age; } /** * 功能:在判定已经是正确的身份证号码之后,查找出此人出生日期 * @param idCard-身份证号码 * @return 出生日期 XXXX MM-DD */ public static String getBirthday(String idCard) { String Ain = ""; if (idCard.length() == 18) { Ain = idCard.substring(0, 17); } else if (idCard.length() == 15) { Ain = idCard.substring(0, 6) + "19" + idCard.substring(6, 15); } String strYear = Ain.substring(6, 10);// 年份 String strMonth = Ain.substring(10, 12);// 月份 String strDay = Ain.substring(12, 14);// 日期 return strYear + "-" + strMonth + "-" + strDay; } }