Maxim Veksler
Maxim Veksler

Reputation: 30232

Joda time timezone parsing with region/city

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?

Upvotes: 3

Views: 3923

Answers (3)

JodaStephen
JodaStephen

Reputation: 63445

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

Upvotes: 2

Maxim Veksler
Maxim Veksler

Reputation: 30232

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")
    );
}

Upvotes: 1

Freiheit
Freiheit

Reputation: 8777

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."

Upvotes: 3

Related Questions