我正在使用 xmlText() 方法获取 XmlObject 的 Xml 表示。XmlDateTime 对象在字符串末尾带有时区偏移量,根据XML Schema: dateTime是有效的。有没有办法强制 XmlObject 使用 Zulu 格式转换为 xml?
得到这个:2002-10-10T12:00:00-05:00 而需要这个:2002-10-10T17:00:00Z
我正在使用 xmlText() 方法获取 XmlObject 的 Xml 表示。XmlDateTime 对象在字符串末尾带有时区偏移量,根据XML Schema: dateTime是有效的。有没有办法强制 XmlObject 使用 Zulu 格式转换为 xml?
得到这个:2002-10-10T12:00:00-05:00 而需要这个:2002-10-10T17:00:00Z
我在询问 XmlDateTime 对象的实例化,因为我不久前遇到了类似的问题。据我所知,将 XmlDateTime 打印到 xml 的方式取决于内部表示的值,而内部表示的值又取决于调用以提供该值的 setter。问题出在 setDate(...) 方法上。
XmlDateTime 的默认实现将日期时间的值在内部保留为使用 GDateBuilder 构建的 org.apache.xmlbeans.GDate。当您在 XmlDateTime 对象上设置日期时,它最终会将值传递给 GDateBuilder。如果您查看 setDate() 方法的来源,javadoc 指出:
Sets the current time and date based on a java.util.Date instance.
The timezone offset used is based on the default TimeZone. (The default TimeZone is consulted to incorporate daylight savings offsets if applicable for the current date as well as the base timezone offset.)
If you wish to normalize the timezone, e.g., to UTC, follow this with a call to normalizeToTimeZone.
由于 XmlDateTime 对象有一个 setGDate(...) 方法,您可以像这样测试 normalize 方法:
XmlDateTime xmlDateTime = XmlDateTime.Factory.newInstance();
xmlDateTime.setStringValue("2002-10-10T12:00:00-05:00");
System.out.println(xmlDateTime.xmlText());
GDateBuilder gdb = new GDateBuilder(xmlDateTime.getDateValue());
gdb.normalize();
xmlDateTime.setGDateValue(gdb.toGDate());
System.out.println(xmlDateTime.xmlText());
对我来说,这是打印的:
<xml-fragment>2002-10-10T12:00:00-05:00</xml-fragment>
<xml-fragment>2002-10-10T17:00:00Z</xml-fragment>
这是我可以让它以 UTC 打印的唯一方法。
我希望有更好的方法,虽然遗憾的是我找不到它......