开发者

Joda time timezone parsing with region/city

开发者 https://www.devze.com 2023-03-26 17:25 出处:网络
import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter;
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.ou开发者_如何学编程t.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?


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消