Converting XMLGregorianCalendar to Date in Java
XMLGregorianCalendar can be transformed into either java.util.Date or java.sql.Date as per the requirements. JAXB (Java API/XML Bindings Architecture) is a common framework for creating XML documents from Java objects and XML files from Java objects. JAXB also allows the XML Schema file to construct Java classes (.XSD file). JAXB maps xs:date, xs:time and xs:dateTime to XMLGregorianCalendar in Java by default, but you can customize XJC to construct java.util.Date objects instead of javax.xml.datatype.xmlGregorianCalendar.
Since java.util.Date is the most common way to deal with Java date and time, we always need to convert the instance of XMLGregorianCalendar to the Java Date instance.
Using the Java API, we can easily convert XMLGregorianCalendar to XMLGregorianCalendar Date and Date in Java.
By the way, it’s nice to note that there are three different forms of XML Schema that can represent either date, time, or both, while java.util.Date includes details about date and time together.
Here is a Java program, which converts XMLGregorianCalendar to Date. So we will take XMLGregorianCalendar and return java.util.Date.
XMLGregorianCalendar from Date in Java : 2021-02-22T17:10:28.732Z java.util.Date from XMLGregorianCalendar in Java : Mon Feb 22 17:10:28 UTC 2021
So now the important points about XMLGregorianCalendar and date:
- XML Schema has various date, time and dateTime data types, e.g. xsd:date, xsd:time and xsd:dateTime, all of which are mapped to XMLGregorianCalendar in Java by default with JAXB XJC.
- When constructing a GregorianCalendar case, it is best to use a constructor instead of calling GregorianCalendar.getInstance() since it is similar to Calendar.getInstance() and can return different calendar types based on local settings, e.g. Thai Local Buddhist Calendar or Japanese Imperial Japan Imperial Calendar. You also exclude typecasting when using a constructor since getInstance() returns the java.util.Calendar instance and prevents ClassCastException in Java.
- For xs:date, xs:time and xs:dateTime data types, you can configure XJC to generate Date instead of XMLGregorianCalendar. I’ll write about that later, but this option can still be explored.
This is all about how to convert the XMLGregorianCalendar to Java Date and XMLGregorianCalendar Date.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.