问题
I'm getting an Xml representation of an XmlObject using the xmlText() method. The XmlDateTime objects are coming out with timezone offsets at the end of the string which is valid according to XML Schema: dateTime. Is there any way to force the XmlObject to convert to xml with the Zulu formatting?
Getting this: 2002-10-10T12:00:00-05:00 and need this instead: 2002-10-10T17:00:00Z
回答1:
I was asking about the instantiation of the XmlDateTime object because I ran into a similar issue a while ago. From what I could figure out, the way the XmlDateTime is printed to xml depends on the value of the internal representation, which in turn depended on the setter which was invoke to provide that value. The issue was with the setDate(...) method.
The default implementation of XmlDateTime keeps the value of the datetime internally as an org.apache.xmlbeans.GDate which is built using a GDateBuilder. When you set the date on the XmlDateTime object it eventually passes the value onto a GDateBuilder. If you look at the source of the setDate() method, the javadoc states that:
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.
Since the XmlDateTime object has a setGDate(...) method you can test the normalize method like this:
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());
For me this printed:
<xml-fragment>2002-10-10T12:00:00-05:00</xml-fragment>
<xml-fragment>2002-10-10T17:00:00Z</xml-fragment>
That was the only way that I could get it to print in UTC.
I hope there is a better way, although sadly I couldn't find it...
来源:https://stackoverflow.com/questions/9468299/xmlbeans-xmldatetime-format-without-timezone-info