采用的版本如下:
基于joda-time进行date format的操作代码如下:
Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); String pattern = "yyyy-MM-dd hh:mm:ss"; DateTime dateTime = new DateTime(calendar); String dateStr = dateTime.toString(pattern); LOGGER.info("dateStr:" + dateStr); DateTime date = DateTimeFormat.forPattern(pattern).parseDateTime(dateStr); LOGGER.info("date:" + date.toDate());
根据pattern创建DateTimeFormatter :
public static DateTimeFormatter forPattern(String s) { return createFormatterForPattern(s); }
具体的创建过程:
private static DateTimeFormatter createFormatterForPattern(String s) { if(s == null || s.length() == 0) throw new IllegalArgumentException("Invalid pattern specification"); DateTimeFormatter datetimeformatter = null; synchronized(cPatternedCache) { datetimeformatter = (DateTimeFormatter)cPatternedCache.get(s); if(datetimeformatter == null) { DateTimeFormatterBuilder datetimeformatterbuilder = new DateTimeFormatterBuilder(); parsePatternTo(datetimeformatterbuilder, s); datetimeformatter = datetimeformatterbuilder.toFormatter(); cPatternedCache.put(s, datetimeformatter); } } return datetimeformatter; }
也就是先根据pattern从map中获取,如果没有的话那么build
那么我们看DateTimeFormatter是否线程安全的?
private final DateTimePrinter iPrinter; private final DateTimeParser iParser; private final Locale iLocale; private final boolean iOffsetParsed; private final Chronology iChrono; private final DateTimeZone iZone; private final Integer iPivotYear; private final int iDefaultYear;没有static 符合线程安全条件,那么同样是线程安全的