Question

I have a java class inside the jar file that is in a JBoss server which invoked through a bash file as follows.

java -cp /com/site/domain/TimeFormatter.jar packOne.subPack.Test

But I got an error when parsing the below date in there.

java.text.ParseException: Unparseable date: "Wed, 29 Jan 2014 21:00:00 GMT"
    at java.text.DateFormat.parse(DateFormat.java:335)

Java CODE :

Date date = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z").parse("Sun, 26 Jan 2014 21:00:00 GMT");
System.out.println("main().date : " + date);

What am I missing here? I read many posts about the misbehaving of the SimpleDateFormat. But this is some thing that I didn't find among those posts.

Note : I thought this is because of the java version change or some thing. But, I executed the same program with different versions in my machine. It worked perfectly. Server java version "1.5.0_22"

locale details :

LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
Was it helpful?

Solution

Works fine for me, and I think it's not a Java version-related issue... but more of a Locale problem :)

Specifying Locale.ENGLISH for your SimpleDateFormat should definitively make it work. For example, you could do:

final Date date = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z", Locale.ENGLISH).parse("Sun, 26 Jan 2014 21:00:00 GMT");

As specified in the javadoc entry for SimpleDateFormat, the date parsing is locale-sensitive. I have to admit that I don't exactly know how your string does not match your Locale, but we can investigate further if... we know what your default Locale actually is :)

OTHER TIPS

The modern Java date and time classes had not quite come out when this question was first asked and answered. I should like to contribute the modern solution that I recommend using nowadays.

    ZonedDateTime dateTime = ZonedDateTime.parse("Wed, 29 Jan 2014 21:00:00 GMT", 
            DateTimeFormatter.RFC_1123_DATE_TIME);

I was about to write the same about the need for a locale as in the other answer, but then I saw the light: your date-time string conforms to the RFC 1123 format. This is built-in with Java-8 and later and therefore also with ThreeTen Backport, the backport of the modern classes to Java 6 and 7. DateTimeFormatter.RFC_1123_DATE_TIME works in English always, independent of locale. So the above is all you need. Tested on a computer with Danish default locale.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top