2011-08-07 50 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