Lots of googling and frustrated colleagues and no solution to represent a simple birth date without minutes and seconds. In short, jaxb always uses XMLGregorianCalendar to represent dates, how to represent the birth date as
1980-01-01
instead of
1980-01-01T00:00:00.000+01:00
This is related to my previous article regarding Fødselsnummer, the Norwegian equivalent of US social security number, extracting birth date from the fødselsnummer.
As this jax-rpc vs jaxb comparison shows, http://www.ibm.com/developerworks/webservices/library/ws-tip-jaxwsrpc2.html, all date related stuff is represented as XMLGregorianCalendar in JAXB. Normally, I work with org.joda.time.DateTime and map to the XMLGregorianCalendar like this.
public static XMLGregorianCalendar dateTimeToXMLGregorianCalendar(
DateTime dateTime) throws DatatypeConfigurationException {
DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
return dataTypeFactory.newXMLGregorianCalendar(dateTime.toGregorianCalendar());
}
What I’ve learned is that it’s of great importance how the XMLGregorianCalendar object is constructed. The solution is simple, but I argue that it’s not very intuitive. I like explicit constructors or static constructors to indicate separate constructors.
public static XMLGregorianCalendar birthDateToXML(DateTime birthDate) throws DatatypeConfigurationException {
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar();
xmlGregorianCalendar.setDay(birthDate.getDayOfMonth());
xmlGregorianCalendar.setMonth(birthDate.getMonthOfYear());
xmlGregorianCalendar.setYear(birthDate.getYear());
return xmlGregorianCalendar;
}
now you may use xsd:date to represent it, instead of xsd:dateTime, in order to improve compatibility with older web services implementing older jaxb versions (with java.util.calendar instead of XMLGregorianCalendar) and/or JAX-RPC.
December 27, 2008 at 1:51 pm |
Thanks.
April 17, 2009 at 6:58 pm |
I used in this way and work fine:
@XmlElement @XmlSchemaType(name=”date”) private Date birthDate;
April 17, 2009 at 7:27 pm |
Did you get that code snippet auto-generated from the xsd using jaxb2? If so, cool! Can I see the xsd? :)
August 11, 2009 at 6:47 am |
After generating the xml i should get the date format in yyyy-mm-dd not with time zone .will it come so …
August 11, 2009 at 8:57 am |
That’s what the post is about and the goal is clearly stated in the first paragraph, the same as your goal, right? Hint: Don´t populate the timezone object (null) in XMLGregorianCalendar.