DateFormatUtils { public static String getRegexPattern(final SimpleDateFormat dateFormat) { final PatternContext pattern = new PatternContext(dateFormat.toPattern()); pattern.replace(Pattern.compile("G+"), dateFormat.getDateFormatSymbols().getEras()); pattern.replace(Pattern.compile("[y]{3,}"), "\\d{4}"); pattern.replace(Pattern.compile("[y]{2}"), "\\d{2}"); pattern.replace(Pattern.compile("y"), "\\d{4}"); pattern.replace(Pattern.compile("[M]{3,}"), dateFormat.getDateFormatSymbols().getMonths(), dateFormat.getDateFormatSymbols().getShortMonths()); pattern.replace(Pattern.compile("[M]{2}"), "\\d{2}"); pattern.replace(Pattern.compile("M"), "\\d{1,2}"); pattern.replace(Pattern.compile("w+"), "\\d{1,2}"); pattern.replace(Pattern.compile("W+"), "\\d"); pattern.replace(Pattern.compile("D+"), "\\d{1,3}"); pattern.replace(Pattern.compile("d+"), "\\d{1,2}"); pattern.replace(Pattern.compile("F+"), "\\d"); pattern.replace(Pattern.compile("E+"), dateFormat.getDateFormatSymbols().getWeekdays(), dateFormat.getDateFormatSymbols().getShortWeekdays()); pattern.replace(Pattern.compile("a+"), dateFormat.getDateFormatSymbols().getAmPmStrings()); pattern.replace(Pattern.compile("H+"), "\\d{1,2}"); pattern.replace(Pattern.compile("k+"), "\\d{1,2}"); pattern.replace(Pattern.compile("K+"), "\\d{1,2}"); pattern.replace(Pattern.compile("h+"), "\\d{1,2}"); pattern.replace(Pattern.compile("m+"), "\\d{1,2}"); pattern.replace(Pattern.compile("s+"), "\\d{1,2}"); pattern.replace(Pattern.compile("S+"), "\\d{1,3}"); pattern.replace(Pattern.compile("z+"), "[a-zA-Z-+:0-9]*"); pattern.replace(Pattern.compile("Z+"), "[-+]\\d{4}"); return pattern.toString(); }  static String getRegexPattern(final SimpleDateFormat dateFormat);  }
@Test public void testSimpleQuotes() { Assert.assertEquals("\\Qdate1\\E\\Qdate2\\E", DateFormatUtils .getRegexPattern(new SimpleDateFormat("'date1''date2'"))); Assert.assertEquals("\\Qdate1\\E \\Qdate2\\E", DateFormatUtils .getRegexPattern(new SimpleDateFormat("'date1' 'date2'"))); }
@Test public void testDoubleQuotes() { Assert.assertEquals("'\\Qdouble quotes\\E'", DateFormatUtils .getRegexPattern(new SimpleDateFormat("'''double quotes'''"))); Assert.assertEquals("'\\Qdouble quotes\\E''", DateFormatUtils .getRegexPattern(new SimpleDateFormat("'''double quotes'''''"))); }
@Test public void testEras() { Date now = new Date(); SimpleDateFormat germanFormat = new SimpleDateFormat("G", Locale.GERMAN); String germanDate = germanFormat.format(now); System.out.println(germanDate); Matcher germanMatcher = Pattern.compile( DateFormatUtils.getRegexPattern(germanFormat)).matcher( germanDate); Assert.assertEquals(true, germanMatcher.matches()); Assert.assertEquals(germanDate, germanMatcher.group()); }