Today I encountered a requirement to determine that the date format is “YYYy.mm.dd”. The code is as follows:

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; Public class DataTest {public static void main (String [] args){String STR = "2019.11.08"; String regex = "[0-9]{4}.[0-9]{2}.[0-9]{2}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); boolean dateFlag = matcher.matches(); if (! DateFlag) {system.out.println (" format mismatch "); return ; } SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); format.setLenient(false); try{ Date date = format.parse(str); System.out.print(" Format correct! ") ); }catch(Exception e){system.out.println (" parsing error! ") ); }}}Copy the code