使用DateFormat.parse()的无法解析的日期

jus*_*der 5 java datetime simpledateformat aem

我在这个网站上遵循了一些其他解决方案来解决这个难题,我没有安装Joda Time,但我仍然不知道为什么会失败.

我也试过去除冒号,正如一个解决方案所说,但这没有帮助.

currentNode.getProperty("jcr:created").getString()= 2013-03-07T11:57:08.596-05:00

我收到此错误:java.text.ParseException:Unparseable date:"2013-03-07T11:57:08.596-05:00"

<%@page import="
    java.util.Date,
    java.text.SimpleDateFormat,
    java.text.DateFormat"
%>
<%
    DateFormat outputFormat = new SimpleDateFormat("MMMM dd, yyyy");
    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    String currentDate = currentNode.getProperty("jcr:created").getString();
    Date date = inputFormat.parse(currentDate); // <-- Failing here
    String currentDateString = outputFormat.format(date);
%>
Run Code Online (Sandbox Code Playgroud)

dru*_*bot 13

形成的时区Z应该是-0500,而不是-05:00.

所以我建议你更换

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Run Code Online (Sandbox Code Playgroud)

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Run Code Online (Sandbox Code Playgroud)

有关可用格式的更多详细信息,请参阅SimpleDateFormat的javadoc.

如果您的jdk不允许X模式,则必须修复输入字符串以删除:.这可以使用正则表达式完成:

currentDate = currentDate.replaceAll(":(\\d\\d)$", "$1")
Run Code Online (Sandbox Code Playgroud)

  • `X`模式是Java 7的新模式. (6认同)