Date.toString得到的字符串转换回日期问题
try {
String testDateStr = "Tue Feb 23 02:01:00 CST 2021";
//指定格式
SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
Date date = sdf1.parse(testDateStr);
//日期转字符串
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatStr = sdf2.format(date);
System.out.println(formatStr);
} catch (ParseException e) {
e.printStackTrace();
}
重点在初始化SimpleDateFormat的时候要使用SimpleDateFormat(String pattern, Locale locale)方法,指定Locale.ENGLISH,否则报错java.text.ParseException: Unparseable date: “Tue Feb 23 02:01:00 CST 2021”