Skip to content

Instantly share code, notes, and snippets.

@zzpmaster
Created June 11, 2019 05:27
Show Gist options
  • Save zzpmaster/feb7201cd6ee4b75cbc930fa3c8f15ab to your computer and use it in GitHub Desktop.
Save zzpmaster/feb7201cd6ee4b75cbc930fa3c8f15ab to your computer and use it in GitHub Desktop.
public class FlexibleDateParser {
private List<ThreadLocal<SimpleDateFormat>> threadLocals = new ArrayList<ThreadLocal<SimpleDateFormat>>();
public FlexibleDateParser(List<String> formats) {
threadLocals.clear();
for (final String format : formats) {
ThreadLocal<SimpleDateFormat> dateFormatTL = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
SimpleDateFormat sdf = new SimpleDateFormat(format);
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
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment