Skip to content
Related Articles

Related Articles

Convert Date to XMLGregorianCalendar in Java
  • Last Updated : 22 Feb, 2021

XML Gregorian Calendar: The rules for specifying dates in XML format are defined in the XML Schema standard. The Java XMLGregorianCalendar class, introduced in Java 1.5, is a representation of the W3C XML Schema 1.0 date/time datatypes and is required to use the XML format. 

In this approach, we have first changed the standard date to Gregorian Calendar date format and then changed it to XML Gregorian Date using the DatatypeFactory(). newInstance method which creates new javax.xml.datatype Objects that map XML to/from Java Objects.

Code:

Java




// Java program to Convert Date to XMLGregorianCalendar
  
// importing neccessary packages
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
  
public class DateToXMLGregorianCalendar {
  
    public static void main(String[] args)
    {
  
        // Create Date Object
        Date current_date = new Date();
  
        // current date time in standard format
        System.out.println("Standard Format :- "
                           + current_date);
  
        XMLGregorianCalendar xmlDate = null;
  
        // Gregorian Calendar object creation
        GregorianCalendar gc = new GregorianCalendar();
  
        // giving current date and time to gc
        gc.setTime(current_date);
  
        try {
            xmlDate = DatatypeFactory.newInstance()
                          .newXMLGregorianCalendar(gc);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
  
        // current date time in XMLGregorain Calendar format
        System.out.println("XMLGregorianCalendar Format :- "
                           + xmlDate);
    }
}
Output
Standard Format :- Tue Feb 16 17:44:25 UTC 2021
XMLGregorianCalendar Format :- 2021-02-16T17:44:25.164Z

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :