Search code examples
javautcxmlgregoriancalendar

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);
}

Solution

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

    DateTimeFormat.forPattern("HH:mm:ss'Z'");