Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve java.text.ParseException: Unparseable date?

I'm trying to convert this to a readable format however, keep getting java.text.ParseException: Unparseable date: "2016-11-18T11:13:43.838Z" (at offset 23)

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
    Date date1 = df.parse("2016-11-18T11:13:43.838Z");

    DateFormat outputFormatter1 = new SimpleDateFormat("dd-MMM-yyyy");
    String output1 = outputFormatter1.format(date1); //
} catch (ParseException e) {
    e.printStackTrace();
}

I read about adding locale as other SO answers suggested but it is still not working.

like image 822
Woppi Avatar asked May 02 '17 11:05

Woppi


2 Answers

you are parsing a string that is not a correct representation of that pattern, you are missing the TimeZone... something like: -0600

example:

Date date1 = df.parse("2016-11-18T11:13:43.838-0600Z");

here is the doc for more info....

your code should look like:

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    try {
        Date date1 = df.parse("2016-11-18T11:13:43.838-0600Z");
        DateFormat outputFormatter1 = new SimpleDateFormat("dd-MMM-yyyy");
        String output1 = outputFormatter1.format(date1); //
    } catch (ParseException e) {
        e.printStackTrace();
    }
like image 160
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 12 '22 23:10

ΦXocę 웃 Пepeúpa ツ


According to the docs the Z in your format string indicates an RFC 822 time zone e.g. +01:00. You need to parse a ISO 8601 Time zone (the Z in your input string indicating UTC timezone). You configure that with X:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
like image 41
Manos Nikolaidis Avatar answered Oct 13 '22 00:10

Manos Nikolaidis