I want to create an XMLGregorianCalendar
with the following characteristics:
So I would expect the date to be printed as: 18:00:00Z (XML Date).
The element is an xsd:time and I want the time to be displayed like this in the XML.
<time>18:00:00Z</time>
But I am getting the following: 21:00:00+0000. I am at -3 offset and the result is the calculation with my offset.
Why is wrong with my code?
protected XMLGregorianCalendar timeUTC() throws Exception {
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ssZZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateS = df.format(date);
return DatatypeFactory.newInstance().newXMLGregorianCalendar(dateS);
}
To get an output you've mentioned (18:00:00Z
) you have to set the XMLGregorianCalendar's timeZone offset to 0 (setTimezone(0)
) to have the Z
appear. You can use the following:
protected XMLGregorianCalendar timeUTC() throws DatatypeConfigurationException {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
XMLGregorianCalendar xmlcal = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(
dateFormat.format(new Date()));
xmlcal.setTimezone(0);
return xmlcal;
}
If you would like to have the full DateTime then:
protected XMLGregorianCalendar timeUTC() throws DatatypeConfigurationException {
return DatatypeFactory.newInstance()
.newXMLGregorianCalendar(
(GregorianCalendar)GregorianCalendar.getInstance(TimeZone.getTimeZone(ZoneOffset.UTC)));
}
The ouput should be something like this: 2017-08-04T08:48:37.124Z