考虑到了线程问题,在一般情况下,用下面这种即可(注释部分为测试线程)
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
public class SimpleDataFormatUtil {
private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 日期转换成字符串
* @param date
* @return
* @throws ParseException
*/
public static String formatDate(Date date)throws ParseException {
synchronized (sdf) {
return sdf.format(date);
}
}
/**
* 字符串转换成日期
* @param strDate
* @return
* @throws ParseException
*/
public static Date parse(String strDate) throws ParseException{
synchronized(sdf){
return sdf.parse(strDate);
}
}
/*private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String formatDate(Date date)throws ParseException{
return sdf.format(date);
}
public static Date parse(String strDate) throws ParseException{
return sdf.parse(strDate);
}*/
/*public static class TestSimpleDateFormatThreadSafe extends Thread {
@Override
public void run() {
while (true) {
try {
this.join(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
System.out.println(this.getName() + ":" + SimpleDataFormatUtil.parse("2015-10-15 16:00:00"));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
for(int i = 0; i < 3; i++){
new TestSimpleDateFormatThreadSafe().start();
}
}*/
}