Understanding JAXB: Java Binding Customization
Subject:   Date problem...
Date:   2003-12-29 17:00:28
From:   hashimisayed
Response to: Date problem...

JAXB maps an xs:date to a java.util.Calendar. Because dates can be represented in various formats, you might have to customize how the date is parsed and what type of object to return after the parsing. Since your dates are not correct, then more than likely the format of your dates does not match what java.util.Calendar is expecting. So, what you want to do is write a little class that parses your dates for you. To do that, you have to write some JAXB customization and a simple class.

Lets assume that you want all the dates in your schema to be treated the same and that when JAXB sees an xs:date it should return a java.util.Date and not the default java.util.Calendar. For simplicity, lets also assume that your dates are formatted as: "yyyy-mm-dd".

1) Add JAXB Customization to the globalBindings section:

<jaxb:javaType name="java.util.Date" xmlType="xs:date" printMethod="SimpleDateFormatter.print" parseMethod="SimpleDateFormatter.parse"/>

2) Write a class that formats the date and returns a java.util.Date.

public class SimpleDateFormatter
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static Date parse(String date)throws ParseException
return dateFormat.parse(date);
public static String print(Date date)
String result = null;
result = dateFormat.format(date);
return result;

A couple of things to realize.

1) If you have to write a class to format and return dates, then you will have to make that class available to the schema compiler when you compile the xsd; you do that by executing the jar file (jaxb-xjc.jar) and using the classpath (-cp) switch.
2) You maybe able to use an existing class. For example, if my dates were really formatted as "yyyy-MM-dd", then you could use java.sql.Date and not have to write a new class and have to deal with (1).
3) Finally, if all of your dates are not formatted the same then you need to write xml simpleTypes for the dates and add customization to each one separately. Here is an example:

<xs:simpleType name="Date">
<jaxb:javaType name="java.sql.Date" xmlType="xs:date" printMethod="valueOf" parseMethod="toString"/>
<xs:restriction base="xs:date"/>


1 to 2 of 2
  1. Date problem...
    2005-03-23 11:26:53  Jaxnitup [View]

  2. Date problem...
    2005-03-22 02:38:57  matmayer [View]

1 to 2 of 2