標籤:
寫了個判斷使用者輸入生日字串是否合法的方法,前提是輸入字串格式為yyyyMMdd。
public static boolean checkBirthDay(String birthday) { if (Common.empty(birthday)) { return false; } if (birthday.length() != 8) { return false; } Pattern pattern = Pattern .compile("^[1,2]\\d{3}(0[1-9]||1[0-2])(0[1-9]||[1,2][0-9]||3[0,1])$"); Matcher matcher = pattern.matcher(birthday); if (!matcher.matches()) { return false; } Date birth = null; try { birth = new SimpleDateFormat("yyyyMMdd").parse(birthday); } catch (ParseException e) { e.printStackTrace(); } if (!new SimpleDateFormat("yyyyMMdd").format(birth).equals(birthday)) { return false; } // 擷取當前日期的毫秒數 long currentTime = System.currentTimeMillis(); // 擷取生日的毫秒數 long birthTime = birth.getTime(); // 如果目前時間小於生日,生日不合法。反之合法 if (birthTime > currentTime) { return false; } return true; }
原文地址:http://www.iyuze.cn/article/609.html
java判斷生日字串是否合法