Solr ThreadLocal DateFormat - Open Source Code Snippet


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 DateFormat
private 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 formats
org.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
      }
    }
}

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)