1、新建实例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by rc on 2017/12/16.
*/
public class DateUtil {
public static String formatDate(Date date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
public static Date parse(String strDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.parse(strDate);
}
}
2、同步SimpleDateFormat对象
package net.tudoutiao.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by rc on 2017/12/16.
*/
public class DateUtil {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String formatDate(Date date) throws ParseException {
synchronized (sdf){
return sdf.format(date);
}
}
public static Date parse(String strDate) throws ParseException {
synchronized (sdf){
return sdf.parse(strDate);
}
}
}
3、使用ThreadLocal
package net.tudoutiao.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by rc on 2017/12/16.
*/
public class DateUtil {
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static String formatDate(Date date) throws ParseException {
return threadLocal.get().format(date);
}
public static Date parse(String strDate) throws ParseException {
return threadLocal.get().parse(strDate);
}
}
package net.tudoutiao.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by rc on 2017/12/16.
*/
public class DateUtil {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
private static DateFormat getDateFormat() {
DateFormat dateFormat = threadLocal.get();
if (dateFormat == null){
dateFormat = new SimpleDateFormat(DATE_FORMAT);
threadLocal.set(dateFormat);
}
return dateFormat;
}
public static String formatDate(Date date) throws ParseException {
return getDateFormat().format(date);
}
public static Date parse(String strDate) throws ParseException {
return getDateFormat().parse(strDate);
}
}
来自:https://www.cnblogs.com/peida/archive/2013/05/31/3070790.html