在需要的時(shí)候創(chuàng)建實(shí)例
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);
}
缺點(diǎn):每次調(diào)用方法都要?jiǎng)?chuàng)建和銷(xiāo)毀sdf對(duì)象,效率較低。
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);
}
}
缺點(diǎn):并發(fā)量大時(shí)線程阻塞,對(duì)性能有影響。
ThreadLocal
ThreadLocal可以讓每個(gè)線程都得到一個(gè)sdf對(duì)象
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(線程安全的類(lèi))
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);
}