Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate XMLGregorianCalendar time as UTC

I want to create an XMLGregorianCalendar with the following characteristics:

  • Time only
  • UTC timezone (The "Z" appended at the end)

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);
}
like image 329
Evandro Pomatti Avatar asked Aug 03 '17 21:08

Evandro Pomatti


People also ask

How to Create object of XMLGregorianCalendar?

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.

How to convert XMLGregorianCalendar into Date?

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.


1 Answers

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

like image 167
mgyongyosi Avatar answered Sep 22 '22 18:09

mgyongyosi