【发布时间】:2019-02-19 07:51:22
【问题描述】:
我正在使用下面的代码来格式化毫秒分辨率的日期字符串。它适用于2018-09-14T13:05:21.329Z,但不适用于2018-09-14T13:05:21.3Z。任何人都可以提出原因以及如何纠正它?
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date parsedDate = formatter.parse(date);
String destDate = sdfDestination.format(parsedDate);
return destDate;
} catch (java.text.ParseException parseException) {
logger.error("Parse Exception occured while converting publication time to date "
+ "format 'yyyy-MM-dd HH:mm:ss'", parseException);
}
我得到以下异常:
java.text.ParseException: Unparseable date: "2018-09-14T13:05:21.3Z"
at java.text.DateFormat.parse(Unknown Source) ~[na:1.8.0_181]
at com.noordpool.api.implementation.utility.Utility.parseDate(Utility.java:136) [classes/:na]
at com.noordpool.api.implementation.utility.Utility.parseMessage(Utility.java:77) [classes/:na]
【问题讨论】:
-
这可能是因为您的
SimpleDateFormat期望在最后的Z之前有 3 位数字,而您失败的String只有 1 位?您是否尝试过在Z(手动)之前用两个额外的零填充它?那么它也会失败吗? -
我建议你避免使用
SimpleDateFormat类。它不仅过时了,而且出了名的麻烦。今天我们在java.time, the modern Java date and time API 中做得更好。 -
@DonaldDuck 请参阅When is it okay to edit answers for “Code Formatting?”(我建议那里的答案也适用于问题)。
-
@OleV.V.我已经根据this answer 阅读过,我的编辑还可以:“不需要 和不正确的缩进”(强调我的)。
标签: java string date simpledateformat dateformatter