2

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"

Denis Sologub
  • 7,277
  • 11
  • 56
  • 123

2 Answers2

2

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

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", ...
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
  • Thanks! I didn't know that 'X' exists. – Denis Sologub Feb 13 '16 at 13:37
  • Sorry, I checked it on old devices (API 16) and it doesn't work. Old Android versions doesn't know 'X' pattern. – Denis Sologub Feb 13 '16 at 14:10
  • 1
    The only piece which stops you from using `Z` is the colon within the timezone. You can remove the colon using another regex, i.e.: `fixedDateTimezone.replaceAll("(\\d\\d):(\\d\\d)$", "$1$2")`. After this manipulation, `Z` will also work for you. _Note the dollar sign at the end of the regex, it makes sure that colon is not removed for minutes or seconds, but rather in the end of the string (i.e. time zone)._ – Alex Shesterov Feb 13 '16 at 15:00
  • Thanks! I made it using substring but ur variant's better I think. – Denis Sologub Feb 13 '16 at 16:11
1

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

Pranavan Maru
  • 481
  • 5
  • 10
  • @OleV.V., when it's in UTC0 it doesn't show the offset, since the offset is 0. When downstream systems reach your endpoint with a string with a timezone offset, then the string will contain that offset in place of Z, which is the ISO format, similar to the date-time string thrown here in the question by OP – Pranavan Maru Mar 27 '23 at 17:24
  • 1
    @OleV.V. okay now I understand what you meant thanks for pointing it out. I have edited the answer to show that. I have also attached another stackoverflow going deep into the nuances of each implementation. `Instant` still is the winner. – Pranavan Maru Mar 27 '23 at 18:25
  • Very nice. Sorry that I cannot upvote again since I already have once. – Ole V.V. Mar 27 '23 at 18:30