Barışcan Kayaoğlu
Barışcan Kayaoğlu

Reputation: 1304

Java simple date formatter for string to date

Can anyone point out what seems to be the problem here?

try {
    Date date = new SimpleDateFormat("Mon, 02 Nov 2015 15:13:00 EET").parse("EEE, dd MMM yyyy hh:mm:ss z");
} catch (ParseException e) {
    e.printStackTrace();
}

and the stacktrace:

java.text.ParseException: Unparseable date: "Mon, 02 Nov 2015 15:13:00 EET" (at offset 26)

I'm suspecting something with the locale that I'm using but I can't be sure. Seems that "z" for timezone not working.

Edit: Sorry the exception was funny earlier, I changed it but forgot to update here.

try {
            Date date = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z", Locale.US).parse("Mon, 02 Nov 2015 15:13:00 EET");
        } catch (ParseException e) {
            e.printStackTrace();
        }

Upvotes: 0

Views: 242

Answers (3)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22264

Such an exception can come from parsing a date with the wrong Locale. For example this date formatter :

SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z", Locale.US);

will successfully parse the example date :

Date date = df.parse("Mon, 02 Nov 2015 15:13:00 EET");

But the following will give the exception you are getting

SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z", Locale.FRENCH);

I would expect the Locale in Android to be chosen according to the language set by the user.

Upvotes: 0

DBug
DBug

Reputation: 2566

After looking at javadoc for SimpleDateFormat, you are using "hh" for hour, which is assumed to be a 12-hour time. Use HH for 24-hour time. Your example as 15 for the hour.

Upvotes: 1

JFPicard
JFPicard

Reputation: 5168

I think you're missing 'z' here.

Try:

Date date = new SimpleDateFormat("Mon, 02 Nov 2015 15:13:00 EET").
        parse("EEE, dd MMM yyyy hh:mm:ss zzz")

Since your timezone is with three characters.

Upvotes: 0

Related Questions