Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unparseable date using DateFormat.parse()

I followed a few other solutions on this site to this dilemma, and I do not have Joda Time installed, but I'm still at a loss as to why this is failing.

I also tried removing the colons, as one solution stated, but that did not help.

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

I get this error: 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);
%>
like image 387
justacoder Avatar asked Mar 19 '13 16:03

justacoder


2 Answers

The time zone formated as Z should be -0500, not -05:00.

So I'd suggest you to replace

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

with

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

See SimpleDateFormat's javadoc for more details on available formats.

If your jdk doesn't allow the X pattern, you'll have to fix the input string to remove the :. This can be done with a regex :

currentDate = currentDate.replaceAll(":(\\d\\d)$", "$1")
like image 97
drunken bot Avatar answered Oct 04 '22 02:10

drunken bot


After testing the solution by drunken bot, I see that a timezone with half hours does not work, like -0530 (India).

So the improved answer therefore is:

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

Note the added XX at the end, now also minutes are taken into account.

like image 33
Mies44 Avatar answered Oct 04 '22 03:10

Mies44