0

I'm trying to parse a date string using joda time and unfortunately I can't find a way to parse the timezone.

Here my latest attempt:

String s = "2013-09-20 13:23:50 Etc/GMT";
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").parseDateTime(s)

results in

java.lang.IllegalArgumentException: Invalid format: "2013-09-20 13:23:50 Etc/GMT" is malformed at "Etc/GMT"

Where is the error in my pattern?

Zounadire
  • 1,496
  • 2
  • 18
  • 38

2 Answers2

4

You should use Joda-Time library with version 2.0 or later.
This feature was added in version 2.
See release notes 1.6 -> 2.0.

  • Allow 'Z' and 'ZZ' in format patterns to parse 'Z' as '+00:00' [2827359]

  • Support parsing of date-time zone IDs like Europe/London

  • Support parsing of date-time zone names like "EST" and "British Summer Time" These names are not unique, so the new API methods on the builder require you to pass in a map listing all the names you want to be able to parse. The existing method is unaltered and does not permit parsing.

Ilya
  • 29,135
  • 19
  • 110
  • 158
  • Turns out my original problem was a nasty classpath problem, that caused an older version of joda time to be used. Thanks for the tip Ilya that pointed me to the right solution. – Zounadire Aug 27 '14 at 08:42
2

To parse datetime string with time zone you can use next for [Java]:

new DateTimeFormatterBuilder()
      // z is timezone name
      .appendPattern("yyyy-MM-dd HH:mm:ss z") 
      // special map to map names to time zones
      .appendTimeZoneName(new HashMap() {{
          put("UTC", DateTimeZone.UTC);
      }}) 
      .toParser

or [Scala]

new DateTimeFormatterBuilder()
      .appendPattern("yyyy-MM-dd HH:mm:ss z")
      .appendTimeZoneName(Map("UTC" -> DateTimeZone.UTC))
      .toParser
terma
  • 1,199
  • 1
  • 8
  • 15