Convert XMLGregorianCalendar to Date Object

5 months ago codedestine 0

XMLGregorianCalendar to Date Object :-

In this tutorial, we will learn to convert XMLGregorianCalendar to Date Object. If you had worked on a project which consume or publish SOAP web services, then you would had faced a problem in converting XMLGregorianCalendar to Date Object and vice versa. Let’s see an implementation with the help of an example  :-

Example :- 

import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class XMLGregorianCalendarToDate {

  private static XMLGregorianCalendar getXMLGregorianCalendar(){
    XMLGregorianCalendar xmlDate = null;
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(new Date()); 

    try{
      xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
    }catch(Exception e){
      e.printStackTrace();
    } 
    return xmlDate;
  }
 
  public static void main(String[] args) {
 
    XMLGregorianCalendar xmlDate = getXMLGregorianCalendar();
 
    /* java.util.Date */
    Date date = xmlDate.toGregorianCalendar().getTime();
    System.out.println("java.util.date :- " + date);
 
    /* java.sql.Date */
    long time = xmlDate.toGregorianCalendar().getTime().getTime();
    java.sql.Date sqlDate = new java.sql.Date(time);
    System.out.println("java.sql.Date :- " + sqlDate);
 
  }

}

Result :-

XMLGregorianCalendar to Date

You can also check :- 

Convert Date to XMLGregorianCalendar Object

Removing Timezone from XMLGregorianCalendar

That’s all for Convert XMLGregorianCalendar to Date Object, If you liked it, please share your thoughts in comments section and share it with others too.