Assume an application that parses thousands of date strings per second using some already known SimpleDateFormat patterns. The application needs to decide dynamically whether each such date pattern has a timezone, i.e. whether the date pattern string contains, anywhere in it and unquoted, the letters Z or X, in either upper case or lower case (i.e., 4 symbols in total).
Examples of such date patterns are:
- yyyy/MM/dd HH:mm:ss.SSS Z // Timezone (not quoted
Zsymbol) - yyyy/MM/dd HH:mm:ss.SSS’Z’ // No timezone (quoted
Zsymbol) - EEE MMM dd HH:mm:ss x yyyy // Timezone (not quoted
xsymbol) - EEE MMM dd HH:mm:ss’x’yyyy // No timezone (quoted
xsymbol)
One way of doing this is by using the indexOf() method of the String class, but this means running the method 4 times on each date pattern (or 2, if the date pattern string is converted to upper or lower case beforehand), plus checking whether the timezone symbol is quoted (in which case the pattern does not actually have a timezone).
The other choice is using a java regular expression, like
String date = ... // Get a SimpleDateFormat pattern
Pattern timezone = Pattern.compile("[^ZzXx]+[^'\"][ZzXx]{1}.*");
if (timezone.matcher(date).matches())
{
// The date pattern does have a timezone
}
Is there a faster version for the above regular expression, i.e., for
"[^ZzXx]+[^'\"][ZzXx]{1}.*"
or any other faster way, in general, for checking whether a SimpleDateFormat pattern does contain a timezone symbol?
I suggest do it as simple as possible: