2011-06-12 63 views
3

我生成的XML格式包含有效的XML格式的日期,我還需要它包含UTC偏移量。格式化XML的日期以包括UTC偏移量

我尤斯groovy,但我會告訴我使用而不是Java代碼(在兩種語言的答案是好的):

Calendar c = Calendar.getInstance(); 
long timeZoneOffset = c.timeZone.getOffset(c.getTimeInMillis())/(1000*60*60); 
SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
formatter.format(c.getTime()) + "+0" + timeZoneOffset + ":00"; 

上面的代碼give4s我2011-06-12T07:23:25.000+03:00,但是這個代碼有兩個問題:

  1. 這是醜陋的,並且可能不是最好的方式做到這一點
  2. 它不會像印度時區工作(GMT +5:30),尼泊爾(GMT +5:45

我試着用new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z")的時區,但它給了我2011-06-12T07:23:25.000+0300這是不正確的格式(+0300代替的+03:00)。

以我需要的方式格式化日期的其他方法? (最好沒有第三方)

回答

2

一個其它替代 - 也埋JAXB API內 - (不需要Jodatime):

Calendar c = ... 
    String printDate = javax.xml.bind.DatatypeConverter.printDateTime(c); 

HTH

+0

謝謝 - 這是最簡單的解決方案,可在任何地方安裝JRE6。 – RonK 2011-06-12 12:23:22

1

我覺得最優雅的方法就是用Joda-Time庫。您需要ISO 8601(第5.4節)格式(如由xs:dateTime XSD型爲代表):

DateTime dt = new DateTime(); 
DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); 
System.out.println(fmt.print(dt)); 

結果:

2011-06-12T07:36:32.294 + 02:00

0

您是否嘗試過使用XMLGregorianCalendar?例如:

Calendar c = ... 
DataTypeFactory f = DataTypeFactory.newInstance(); 
XMLGregorianCalendar xc = f.newXMLGregorianCalendar(c); 
String str = xc.toXMLFormat(); 

如果日曆日期時間與時區偏移,則偏移時區中應包括格式化爲每XML數據類型規範的結果字符串。