Java 身份證判斷性別獲取年齡
阿新 • • 發佈:2018-07-27
integer 系統時間 current card throws class except .com unit
import com.alibaba.fastjson.JSON; import org.junit.Test; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author ceshi * @Title: CardJunitTest * @ProjectName CardJunitTest * @Description: TODO * @date 2018/7/2622:53 */ public class CardJunitTest {private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); @Test public void test(){ try { System.out.println(JSON.toJSON(identityCard18("**********"))); System.out.println(JSON.toJSON(identityCard15("*********"))); }catch (Exception e){ e.printStackTrace(); } }/** * 18位身份證獲取性別和年齡 * @param CardCode * @return * @throws Exception */ public static Map<String, Object> identityCard18(String CardCode) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); // 得到年份 String year = CardCode.substring(6).substring(0, 4);// 得到月份 String month = CardCode.substring(10).substring(0, 2); //得到日 //String day=CardCode.substring(12).substring(0,2); String sex; // 判斷性別 if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) { sex = "女"; } else { sex = "男"; } // 得到當前的系統時間 Date date = new Date(); // 當前年份 String currentYear = format.format(date).substring(0, 4); // 月份 String currentMonth = format.format(date).substring(5, 7); //String currentdDay=format.format(date).substring(8,10); int age = 0; // 當前月份大於用戶出身的月份表示已過生日 if (Integer.parseInt(month) <= Integer.parseInt(currentMonth)) { age = Integer.parseInt(currentYear) - Integer.parseInt(year) + 1; } else { // 當前用戶還沒過生日 age = Integer.parseInt(currentYear) - Integer.parseInt(year); } map.put("sex", sex); map.put("age", age); return map; } /** * 15位身份證獲取性別和年齡 * @param card * @return * @throws Exception */ public static Map<String, Object> identityCard15(String card) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); //年份 String year = "19" + card.substring(6, 8); //月份 String yue = card.substring(8, 10); //日 //String day=card.substring(10, 12); String sex; if (Integer.parseInt(card.substring(14, 15)) % 2 == 0) { sex = "女"; } else { sex = "男"; } // 得到當前的系統時間 Date date = new Date(); //當前年份 String currentYear = format.format(date).substring(0, 4); //月份 String currentMonth = format.format(date).substring(5, 7); //String fday=format.format(date).substring(8,10); int age = 0; //當前月份大於用戶出身的月份表示已過生日 if (Integer.parseInt(yue) <= Integer.parseInt(currentMonth)) { age = Integer.parseInt(currentYear) - Integer.parseInt(year) + 1; } else { // 當前用戶還沒過生日 age = Integer.parseInt(currentYear) - Integer.parseInt(year); } map.put("sex", sex); map.put("age", age); return map; } }
運行結果:
Java 身份證判斷性別獲取年齡