JAXB binds all three of the schema types xsd:date
, and to xsd:time
xsd:dateTime
XMLGregorianCalendar
. This is the javax.xml.datatype
. (Do not confuse the this with java.util.GregorianCalendar
.) There is a convenient set of methods for getting in the various components such as year or day or minute. But creating the These values isn ' t quite so simple because are an XMLGregorianCalendar
abstract class. We ll illustrate this with a simple example for marshalling date and time.
The XML schema snippet shown below defines an element containing sub-elements with xsd:date
and xsd:time
.
<Xsd:complextypename= "Datetimetype"> <xsd:sequence> <xsd:elementname= "Date"type= "Xsd:date"/> <xsd:elementname= "Time"type= "Xsd:time"/> </xsd:sequence></Xsd:complextype>
The generated class contains the usual getters and setters:
Public classDatetimetype {protectedXmlgregoriancalendar date; protectedXmlgregoriancalendar time; PublicXmlgregoriancalendar getDate () {returndate; } Public voidsetDate (Xmlgregoriancalendar value) { This. Date =value; } PublicXmlgregoriancalendar GetTime () {returnTime ; } Public voidsettime (Xmlgregoriancalendar value) { This. Time =value; }}
However, some work remains to be do before we can call either setter. It's the class that javax.xml.datatype.DatatypeFactory
provides the methods with which we can create the javax.xml.datatype.XMLGregorianCalendar
objects.
//Create a Datetimetype element for the current time and date.Objectfactory of =Newobjectfactory ();D atetimetype Meta=Of.createdatetimetype (); GregorianCalendar Now=NewGregorianCalendar ();//obtain a datatypefactory instance.Datatypefactory DF =datatypefactory.newinstance ();//Create an Xmlgregoriancalendar with the current date.Xmlgregoriancalendar gcdate =df.newxmlgregoriancalendardate (Now.get (calendar.year), Now.get (Calendar.month), Now.get ( Calendar.day_of_month), datatypeconstants.field_undefined);//Create an Xmlgregoriancalendar with the current time.Xmlgregoriancalendar Gctime =Df.newxmlgregoriancalendartime (Now.get (Calendar.hour_of_day), Now.get (Calendar.minute), Now.get (Calendar.second),NULL,//No fractiondatatypeconstants.field_undefined);//Insert sub-elements into the datetimetype element.meta.setdate (gcdate); Meta.settime (gctime);
Noticed the argument in the null
method constructing a with the time XMLGregorianCalendar
. This indicates, we don ' t care is about fractions of seconds. It is, however, not possible to omit seconds entirely.
The XML element produced by this code would look like this:
< DateTime > < Date >2008-07-23</Date> <time> 18:42:24</time></DateTime>
You should notice that the date and time representations follow ISO 8601.
Jaxb-xml Schema Types, Date and time