To convert between java.util.Date and XMLGregorianCalendar in Java, you can use the javax.xml.datatype package, which provides classes for handling XML data types, including XMLGregorianCalendar. Here's how you can perform the conversion:
import java.util.Date; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; public class DateToXMLGregorianCalendar { public static void main(String[] args) throws Exception { // Create a java.util.Date instance Date date = new Date(); // Convert java.util.Date to XMLGregorianCalendar XMLGregorianCalendar xmlGregorianCalendar = convertDateToXMLGregorianCalendar(date); // Print the XMLGregorianCalendar System.out.println("XMLGregorianCalendar: " + xmlGregorianCalendar); } public static XMLGregorianCalendar convertDateToXMLGregorianCalendar(Date date) throws Exception { // Get an instance of DatatypeFactory DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); // Convert the java.util.Date to XMLGregorianCalendar // Pass the time in milliseconds since the epoch to the newXMLGregorianCalendar() method return datatypeFactory.newXMLGregorianCalendar(date.getTime()); } } import java.util.Date; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; public class XMLGregorianCalendarToDate { public static void main(String[] args) throws Exception { // Create an XMLGregorianCalendar instance XMLGregorianCalendar xmlGregorianCalendar = getXMLGregorianCalendar(); // Convert XMLGregorianCalendar to java.util.Date Date date = convertXMLGregorianCalendarToDate(xmlGregorianCalendar); // Print the java.util.Date System.out.println("java.util.Date: " + date); } public static Date convertXMLGregorianCalendarToDate(XMLGregorianCalendar xmlGregorianCalendar) throws Exception { // Convert XMLGregorianCalendar to java.util.Date return xmlGregorianCalendar.toGregorianCalendar().getTime(); } public static XMLGregorianCalendar getXMLGregorianCalendar() throws Exception { // Create an XMLGregorianCalendar instance for the current date and time return DatatypeFactory.newInstance().newXMLGregorianCalendar(); } } In these examples:
To convert from java.util.Date to XMLGregorianCalendar, you create an instance of DatatypeFactory, and then use the newXMLGregorianCalendar(long timeInMillis) method to convert the java.util.Date to an XMLGregorianCalendar by passing the time in milliseconds since the epoch.
To convert from XMLGregorianCalendar to java.util.Date, you use the toGregorianCalendar().getTime() method to extract the Date from the XMLGregorianCalendar.
These conversions can be handy when working with XML-based APIs, such as JAXB, which may use XMLGregorianCalendar for date and time representation.
python-multiprocessing grand-central-dispatch embedded-documents type-mismatch webview richtextbox mobile-application ansible-facts primeng spark-structured-streaming