在需要的时候创建实例
public static String format(Date date) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
public static Date parse(String strDate) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.parse(strDate);
}
缺点:每次调用方法都要创建和销毁sdf对象,效率较低。
synchronized
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String format(Date date) throws Exception {
synchronized(sdf){
return sdf.format(date);
}
}
public static Date parse(String strDate) throws Exception {
synchronized(sdf){
return sdf.parse(strDate);
}
}
缺点:并发量大时线程阻塞,对性能有影响。
ThreadLocal
ThreadLocal可以让每个线程都得到一个sdf对象
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static Date parse(String strDate) throws Exception {
return threadLocal.get().parse(strDate);
}
public static String format(Date date) throws Exception {
return threadLocal.get().format(date);
}
基于JDK1.8的DateTimeFormatter(线程安全的类)
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static String format(LocalDateTime date) throws Exception {
return dtf.format(date);
}
public static LocalDateTime parse(String strDate) {
return LocalDateTime.parse(strDate, dtf);
}