2011-08-07 49 views
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") 
     ); 
    } 
} 

我希望它可以解析哥本哈根時區的日期,但它失敗:喬達時間時區與區域分析/城市

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) 

爲什麼?

+0

只加@ Michael-O:爲什麼? – home

+1

由於文檔說: 區域:'Z'輸出不帶冒號的偏移量,'ZZ'用冒號輸出偏移量,'ZZZ'或更多輸出區域ID。 –

回答

3

JodaTime DateTimeFormat javadocsDateTimeFormat你應該使用ZZZ而不是Z。由於該文檔中的表格只顯示Z,所以很容易丟失。「Zone:'Z'輸出不帶冒號的偏移量,'ZZ'用冒號輸出偏移量'ZZZ '或更多輸出區域ID。「

+0

嘗試ZZZ仍爲我引發相同的異常:「」「線程中的異常」main「java.lang.IllegalArgumentException:格式無效:」19:30 29 8 11歐洲/哥本哈根「在」歐洲/哥本哈根「 「 –

+0

Hrmm。我在文檔中看到,我鏈接到「區域名稱:時區名稱('z')無法解析。」,所以也許Joda只能輸出區域但不解析它? – Freiheit

+0

看起來你必須自己對字符串進行一些預處理。 http://joda-interest.219941.n2.nabble.com/Re-Parsing-short-timezones-td5786347.html。它可能,但一年前沒有支持。 – Freiheit

1

我使用的解決方案,這似乎是工作迄今:

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

我認爲這個距離你會很近。你可以寫一個正則表達式來解析出時區,'/。*?\ /.*? /'。然後將它提供給'DateTimeZone.forId(strId)'來驗證它。最後按照上面的格式與其他格式一起進行調用,再加上附加的'withZone'。 – Freiheit

2

解析時區的ID,如歐洲/哥本哈根在喬達時間2.0