3
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        System.out.println(
                DateTimeZone.forID("Europe/Copenhagen")
        );

        DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm dd MM YY Z");
        System.out.println(
                formatter.parseDateTime("19:30 29 8 11 Europe/Copenhagen")
        );
    }
}

I would expect this to to parse the date in Copenhagen timezone, and yet it fails with:

Europe/Copenhagen
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "19:30 29 8 11 Europe/Copenhagen" is malformed at "Europe/Copenhagen"
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:683)
    at Main.main(Main.java:13)

Why?

Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151
  • 1
    Because the docs say: Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with a colon, 'ZZZ' or more outputs the zone id. – Michael-O Aug 07 '11 at 14:56

3 Answers3

3

Looking at the JodaTime DateTimeFormat javadocs for DateTimeFormat you should use ZZZ not Z.

Its easy to miss since the table in that doc only shows Z. Down the page a bit is this, "Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with a colon, 'ZZZ' or more outputs the zone id."

Freiheit
  • 8,408
  • 6
  • 59
  • 101
  • Trying ZZZ still throws the same exception for me: """Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "19:30 29 8 11 Europe/Copenhagen" is malformed at " Europe/Copenhagen"""" – Maxim Veksler Aug 08 '11 at 11:49
  • Hrmm. I see in the doc I linked that "Zone names: Time zone names ('z') cannot be parsed.", so maybe Joda can only output the zone but not parse it? – Freiheit Aug 08 '11 at 13:39
  • Looks like you have to do some preprocessing of the string on your own. http://joda-interest.219941.n2.nabble.com/Re-Parsing-short-timezones-td5786347.html . Its possible, but not supported as of a year ago. – Freiheit Aug 08 '11 at 14:23
2

Parsing of time zone IDs like Europe/Copenhagen was only added in Joda-Time v2.0

JodaStephen
  • 60,927
  • 15
  • 95
  • 117
1

The solution I'm using, which seems to be working so far is:

public static void main(String[] args) {
    DateTimeFormatter formatterC = DateTimeFormat.forPattern("HH:mm dd M YY").withZone(DateTimeZone.forID("Europe/Copenhagen"));
    System.out.println(
        formatterC.parseDateTime("19:30 29 8 11")
    );
}
Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151
  • I think this is as close as you'll get. You can write a regex to parse out the time zone, `/ .*?\/.*? /`. Then feed that into `DateTimeZone.forId(strId)` to validate it. Finally make a call as you did above with the rest of the format, plus the additional `withZone`. – Freiheit Aug 08 '11 at 14:26