Denis Steinman
Denis Steinman

Reputation: 7799

Cannot parse ISO-8601 date string to Date

I looked similar topics but it didn't help me. I have ISO-8601 date type, for example: 2014-08-13T19:05:22.168083+00:00.
I try to parse it so:

public static Date parseISO8601(final String date) {
    String fixedDate = date.replaceFirst("(\\d\\d[\\.,]\\d{3})\\d+", "$1");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH);

    try {
        return df.parse(fixedDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return null;
}

but it throws exception. And I cannot understand why?
Error message: java.text.ParseException: Unparseable date: "2014-08-13T19:05:22.148+00:00"

Upvotes: 2

Views: 1765

Answers (2)

Pranavan Maru
Pranavan Maru

Reputation: 491

If your java version supports Instant, OffsetDateTime, ZonedDateTime, You could simply do:

Instant.parse("2023-03-25T05:23:07.795Z");

Instant is the simplest of the three options available. To read more on the nuances of each, check this stackoverflow question

Upvotes: 1

Alex Shesterov
Alex Shesterov

Reputation: 27525

Use X instead of Z for time zone, i.e.:

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", ...

Upvotes: 2

Related Questions