How to generate XMLGregorianCalendar time as UTC
Asked Answered
E

2

6

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);
}
Economics answered 3/8, 2017 at 21:21 Comment(0)
E
0

Adding 'Z' at the end of he pattern will do the job.

DateTimeFormat.forPattern("HH:mm:ss'Z'");
Economics answered 4/8, 2017 at 12:15 Comment(0)
R
8

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

Rowdyism answered 4/8, 2017 at 8:51 Comment(3)
I have updated my question, I need the date to be formatted like this <time>18:00:00Z</time> in the XML.Economics
I have updated my answer, please check it. It works on my side!Rowdyism
It works! As I am using Java 6 I had to set the timezone like this TimeZone.getTimeZone("UTC")Economics
E
0

Adding 'Z' at the end of he pattern will do the job.

DateTimeFormat.forPattern("HH:mm:ss'Z'");
Economics answered 4/8, 2017 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.