Created
June 11, 2019 05:27
-
-
Save zzpmaster/feb7201cd6ee4b75cbc930fa3c8f15ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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