为了有一个公用的时间处理工具,就封装了一个,该封装的工具是线程安全的,可以放心使用。
public class SafeDateFormat {
final static Map<String, ThreadLocal<DateFormat>> threadLocalPool = new HashMap<>();
final static ThreadLocal<DateFormat> DefaultThreadLocal = new ThreadLocal<DateFormat>() {
@Override
protected synchronized DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
static {
threadLocalPool.put("yyyy-MM-dd HH:mm:ss", DefaultThreadLocal);
}
public static Date parse(String dateStr) throws ParseException {
return DefaultThreadLocal.get().parse(dateStr);
}
public static Date parse(final String format, String dateStr) throws ParseException {
ThreadLocal<DateFormat> threadLocal = threadLocalPool.get(format);
if (threadLocal == null) {
threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected synchronized DateFormat initialValue() {
return new SimpleDateFormat(format);
}
};
threadLocalPool.put(format, threadLocal);
}
return threadLocal.get().parse(dateStr);
}
public static String format(Date date) {
return DefaultThreadLocal.get().format(date);
}
public static String format(final String format, Date date) {
ThreadLocal<DateFormat> threadLocal = threadLocalPool.get(format);
if (threadLocal == null) {
threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected synchronized DateFormat initialValue() {
return new SimpleDateFormat(format);
}
};
threadLocalPool.put(format, threadLocal);
}
return threadLocal.get().format(date);
}