Java – threetenbp: Resolves exceptions when parsing dates with time zone names

threetenbp: Resolves exceptions when parsing dates with time zone names… here is a solution to the problem.

threetenbp: Resolves exceptions when parsing dates with time zone names

I’m trying to parse dates in EEE, dd MMM yyyy HH:mm:ss zzz format, e.g. a string using threeten’s DateTimeFormatter, e.g. “Tue, 16 May 2017 07:44:48 GMT”. However, it seems that for some reason the timezone name can’t be resolved (I tried parsing the same string without the timezone name part and it works).

Here’s the parsing part of the code:

DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
ZonedDateTime parsedDate = ZonedDateTime.parse(date, parseFormatter);

I get the following error:

org.threeten.bp.format.DateTimeParseException: Text ‘Tue, 16 May 2017
13:02:16 GMT’ could not be parsed at index 26

I tried various different formats (e.g. z, zzz, z, zzz) for the time zone name part, but nothing worked. Similarly, if I parse a substring date (to LocalDateTime) that doesn’t have a timezone name part, then it works, so I’m sure the problem is with the timezone name. Does anyone know what the problem is?

Solution

I don’t know why your code doesn’t work. This happens when I use the java.time class in my Java 8. So this is just speculation about a possible fix :

    DateTimeFormatter parseFormatter = DateTimeFormatter.RFC_1123_DATE_TIME;
    ZonedDateTime parsedDate = ZonedDateTime.parse(date, parseFormatter);

You’ll notice that it’s slightly simplified at the same time.

DateTimeFormatter.RFC _1123_DATE_TIME recorded as

Returns the RFC-1123 date-time formatter, such as ‘Tue, 3 Jun 2008
11:05:30 GMT’.

So I think it should accept GMT as the timezone name. I should say it works for your date string, it works for my computer as well. I believe this formatter uses abbreviations for day of the week and month regardless of locale (or you can try DateTimeFormatter.RFC_1123_DATE_TIME.withLocale(Locale.ENGLISH), but I don’t really think it would be necessary).

That said, they say you should avoid three- and four-letter time zone abbreviations. Some are ambiguous, some are not full time zones, which leads to further ambiguity. While GMT is not the most dangerous, a surefire solution to your problem is if you can get a date string with an offset, such as +00:00 or just Z, instead of a three-letter zone name.

See the question and the two examples in this answer, running live at IdeOne.com.

Related Problems and Solutions