我们是否知道是否存在输出与 相同结果的等效格式字符串DateTimeFormatter.ISO_OFFSET_DATE_TIME?
IE
ZonedDateTime dateTime = ZonedDateTime.now();
System.out.println(dateTime.format(DateTimeFormatter.ofPattern(pattern)));
System.out.println(dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
Run Code Online (Sandbox Code Playgroud)
会输出相同的
我正在使用Java 1.7。
尝试转换:
2018-05-23T23:18:31.000Z
Run Code Online (Sandbox Code Playgroud)
进入
2018-05-23 23:18:31
Run Code Online (Sandbox Code Playgroud)
DateUtils类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
尝试使用它时:
String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z");
System.out.println(convertedDate);
Run Code Online (Sandbox Code Playgroud)
得到以下异常:
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)
Run Code Online (Sandbox Code Playgroud)
我可能做错了什么?
有没有更简单的方法(例如Apache Commons lib)?