SimpleDateFormat是线程不安全的,这里给出一个解决方案:
package com.bailian.middleware.util;
import java.text.SimpleDateFormat;
public class DateUtils {
private static final ThreadLocal <SimpleDateFormat> threadLocal = new ThreadLocal <SimpleDateFormat>();
private static final Object object = new Object();
/**
* 拿到指定输出格式的SimpleDateFormat
*
* @param pattern
* @return
*/
public static SimpleDateFormat getSimpleDateFormat(String pattern) {
SimpleDateFormat dateFormat = threadLocal.get();
if (dateFormat == null) {
synchronized (object) {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(pattern);
dateFormat.setLenient(false);
threadLocal.set(dateFormat);
}
}
}
dateFormat.applyPattern(pattern);
return dateFormat;
}
}
通过调用getSimpleDateFormat(String pattern) 来指定格式,例:
DateUtils.getSimpleDateFormat("yyMMdd")