I agree with Kragen that in the general case there is no correct solution. However, if the following conditions hold, you may use the solution below:
1) You have a the set of all possible formats
2) There is no ambiguity between the formats; no date expression can be successfully parsed by two of them.
Consider the following solution which iterates over a list of possible formats. This solution makes use of ThreadLocal, in order to make date parsing efficient in a multithreaded environment (remember that SimpleDateFormat isn't thread safe):
public class FlexibleDateParser {
private List<ThreadLocal<SimpleDateFormat>> threadLocals = new ArrayList<ThreadLocal<SimpleDateFormat>>();
public FlexibleDateParser(List<String> formats, final TimeZone tz){
threadLocals.clear();
for (final String format : formats) {
ThreadLocal<SimpleDateFormat> dateFormatTL = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(tz);
sdf.setLenient(false);
return sdf;
}
};
threadLocals.add(dateFormatTL);
}
}
public Date parseDate(String dateStr) throws ParseException {
for (ThreadLocal<SimpleDateFormat> tl : threadLocals) {
SimpleDateFormat sdf = tl.get();
try {
return sdf.parse(dateStr);
} catch (ParseException e) {
// Ignore and try next date parser
}
}
// All parsers failed
return null;
}
}