Menu

XMLGregorianCalendar instantiation in Java

Goal

Instantiation of a XMLGregorianCalendar in Java

Description

This is more like a reminder than a full recipe but still has its use and importance. Therefore, in this recipe, you’ll learn a quick and easy way to instantiate a XMLGregorianCalendar instance, which is usually associated to a date type field on a WS integrations when using JAX-WS

How to

Simply write the following instructions (adapt to your own needs):

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar
final GregorianCalendar now = new GregorianCalendar();
// in case you need to set the date with a given java.util.Date instance
// now.setTime(date);
DatatypeFactory.newInstance().newXMLGregorianCalendar(now);

In case you use Joda time in your project, you can also do something such as:

...
import org.joda.time.DateTime;
// in case you need to set the date with a given java.util.Date instance
// final DateTime now = new DateTime(date);
final DateTime now = new DateTime();
DatatypeFactory.newInstance().newXMLGregorianCalendar(now.toGregorianCalendar());