Interface DateTimeMatcher
- All Known Implementing Classes:
ListDateTimeMatcher
,RegexDateTimeMatcher
,SimpleDateFormatMatcher
,StartsWithDigitsDateTimeMatcher
A utility class that can be used to determine whether or not a String matches a given date/time format, as specified
by the Time Format used in SimpleDateFormat
. It is not uncommon to see code written along the lines of:
final String format = "yyyy/MM/dd HH:mm:ss.SSS";
try {
new SimpleDateFormat(format).parse(text);
return true;
} catch (Exception e) {
return false;
}
This approach, however, is frowned upon for two important reasons. Firstly, the performance is poor. A micro-benchmark that involves executing
the above code (even reusing the SimpleDateFormat object) to evaluate whether or not text
is a timestamp took approximately 125-130 seconds
to iterate 1,000,000 times (after discarding the first 1,000,000 iterations as a 'warmup'). As a comparison, this utility takes about 8-11 seconds against
the same data and on the same machine.
Secondly, the above snippet has a very expensive side effect of throwing an Exception if the text does not match the format. This Exception is silently ignored, but can have devastating effects on the JVM as a whole, as creating the Exception object can result in requiring a Safepoint, which means that all threads in the JVM may be forced to pause.
Note, however, that this class is not intended to replace SimpleDateFormat, as it does not perform the actual parsing but instead only determines whether or not a given input text matches the pattern, so that if it does, a SimpleDateFormat can be used parse the input.
-
Method Summary
Modifier and TypeMethodDescriptionstatic DateTimeMatcher
boolean
Determines whether or not the text matches the pattern
-
Method Details
-
matches
Determines whether or not the text matches the pattern- Parameters:
text
- the text to evaluate- Returns:
true
if the text matches the pattern,false
otherwise
-
compile
-