import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.regex.Pattern; /** * Created by zengxc on 2018/1/30. */ public class DatePatternUtils { private Boolean checkDate(String dateStr) throws IOException { // 4種分隔符 String sep = "[-\\./_]"; // 年份 String strPattern = "^(19[4-9]\\d|20\\d{2})"; strPattern += "("; // 月(1,3,5,7,8,10,12) strPattern += "((0?[13578]|1[02])(0?[1-9]|[12][0-9]|3[01]))|"; // 月(4,6,9,11) strPattern += "((0?[469]|11)(0?[1-9]|[12][0-9]|30))|"; // 月(2) strPattern += "((0?[2]|11)(0?[1-9]|[12][0-9]|29))|"; strPattern += ")$"; System.out.println(strPattern); Pattern p = Pattern.compile(strPattern); return p.matcher(dateStr).matches(); } /** * 正則校驗時間格式儘可能完善版 ,適用格式(yyyyMMdd),二月只能控制到29號,沒法區分平年、閏年。 * @param dateStr * @return */ private Boolean checkDates(String dateStr){ String datePattern = "^(19[4-9]\\d|20\\d{2})(((0?[13578]|1[02])(0?[1-9]|[12][0-9]|3[01]))" + "|((0?[469]|11)(0?[1-9]|[12][0-9]|30))|((0?[2]|11)(0?[1-9]|[12][0-9]|29))|)$"; Pattern pattern = Pattern.compile(datePattern); return pattern.matcher(dateStr).matches(); } @Test public void test01() throws IOException { String dateStr = "20180229"; Boolean bool = checkDates(dateStr); System.out.println(bool); }