In java you there is a javax.xml.datatype.DatatypeFactory
which can be used to import and export xml dates as follows.
String xmlDateIn = "1900-01-01T12:00:00";
DatatypeFactory df = DatatypeFactory.newInstance();
XMLGregorianCalendar xmlCalendar = df.newXMLGregorianCalendar(xmlDateIn);
String xmlDateOut = xmlCalendar.toXMLFormat();
In this simple case xmlDateIn
equals xmlDateOut
, as expected. But if I want it as a java.lang.Date
things get interesting.
GregorianCalendar gregorianCalendar = xmlCalendar.toGregorianCalendar();
Date dts = gregorianCalendar.getTime();
System.out.println(dts); // prints Mon Jan 01 12:00:00 CET 1900
It still works fine at first sight, but actually internally something seems to be broken. With my IDE I can see what is going on inside the Date
object. (In case you wonder, I live in CET timezone.) Look at this strange time zone.
And when I try to convert this back to XML, the 9 minutes time zone actually gets printed as well. So, it's not just an internal thing.
DatatypeFactory df2 = DatatypeFactory.newInstance();
GregorianCalendar gc2 = new GregorianCalendar();
gc2.setTime(dts);
XMLGregorianCalendar xc2 = df2.newXMLGregorianCalendar(gc2);
System.out.println(xc2.toXMLFormat()); // prints 1900-01-01T12:00:00.000+00:09
In an attempt to fix it, if I set a timezone manually, things get really bad. Look at this magic hour:
String xmlDateIn = "1900-01-01T12:00:00";
DatatypeFactory df = DatatypeFactory.newInstance();
XMLGregorianCalendar xmlCalendar = df.newXMLGregorianCalendar(xmlDateIn);
xmlCalendar.setTimezone(0); // <--- ONLY CHANGE
GregorianCalendar gregorianCalendar = xmlCalendar.toGregorianCalendar();
Date dts = gregorianCalendar.getTime();
Actually I have a workaround for my specific program: What works for me right now, is that I don't set a timezone when I import the xml. The Date
then carries the wrong timezone internally, i.e. 9 minutes. Then when I finally want to export the Date
back to xml, I do set the timezone to 0 on the xml gregorian calendar, and that magically fixes it and exports the correct xml format again.
But really, I was wondering if there is any good explanation for this crazy behavior.