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);
}
In order to generate a new instance of XMLGregorianCalendar, we use a DataTypeFactory from the javax. xml. datatype package. As previously noted, an XMLGregorianCalendar instance has the possibility of having timezone information.
The simplest way to format XMLGregorianCalendar is to first convert it to the Date object, and format the Date to String. XMLGregorianCalendar xCal = ..; //Create instance Date date = xCal. toGregorianCalendar(). getTime(); DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a z"); String formattedString = df.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With