我正在使用 Java 1.7。
尝试转换:
2018-05-23T23:18:31.000Z
进入
2018-05-23 23:18:31
日期实用程序类:
public class DateUtils {
public static String convertToNewFormat(String dateStr) throws ParseException {
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
sdf.setTimeZone(utc);
Date convertedDate = sdf.parse(dateStr);
return convertedDate.toString();
}
}
尝试使用它时:
String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z");
System.out.println(convertedDate);
得到以下异常:
Exception in thread "main" java.text.ParseException: Unparseable date: "2018-05-23T23:22:16.000Z"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.myapp.utils.DateUtils.convertToNewFormat(DateUtils.java:7)
我可能做错了什么?
有没有更简单的方法(例如 Apache Commons lib)?
原文由 PacificNW_Lover 发布,翻译遵循 CC BY-SA 4.0 许可协议
尝试这个。您必须使用一种模式进行解析,另一种模式进行格式化。