The good part of open source project is that you can read the code and learn from it. I write down the good code I learned recently here, so I refer this later.
ThreadLocal DateFormatprivate static class org.apache.solr.common.util.DateUtil.ThreadLocalDateFormat
extends ThreadLocal<DateFormat> {
DateFormat proto;
public ThreadLocalDateFormat() {
super();
SimpleDateFormat tmp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
tmp.setTimeZone(UTC);
proto = tmp;
}
protected DateFormat initialValue() {
return (DateFormat) proto.clone();
}
}
public static DateFormat getThreadLocalDateFormat() {
return fmtThreadLocal.get();
}
private static ThreadLocalDateFormat fmtThreadLocal = new ThreadLocalDateFormat();
Support multiple date formatsorg.apache.solr.common.util.DateUtil
static {
DEFAULT_DATE_FORMATS.add("yyyy-MM-dd'T'HH:mm:ss'Z'");
DEFAULT_DATE_FORMATS.add("yyyy-MM-dd'T'HH:mm:ss");
DEFAULT_DATE_FORMATS.add("yyyy-MM-dd");
DEFAULT_DATE_FORMATS.add("yyyy-MM-dd hh:mm:ss");
DEFAULT_DATE_FORMATS.add("yyyy-MM-dd HH:mm:ss");
DEFAULT_DATE_FORMATS.add("EEE MMM d hh:mm:ss z yyyy");
DEFAULT_DATE_FORMATS.addAll(DEFAULT_HTTP_CLIENT_PATTERNS);
}
public static Date parseDate(String d, Collection<String> fmts) throws ParseException {
if (d.endsWith("Z") && d.length() > 20) {
return getThreadLocalDateFormat().parse(d);
}
return parseDate(d, fmts, null);
}
public static Date parseDate(String dateValue, Collection dateFormats, Date startDate)
throws ParseException {
Iterator formatIter = dateFormats.iterator();
while (formatIter.hasNext()) {
String format = (String) formatIter.next();
if (dateParser == null) {
dateParser = new SimpleDateFormat(format, Locale.ROOT);
dateParser.setTimeZone(GMT);
dateParser.set2DigitYearStart(startDate);
} else {
dateParser.applyPattern(format);
}
try {
return dateParser.parse(dateValue);
} catch (ParseException pe) {
// ignore this exception, we will try the next format
}
}
}