Monday, November 18, 2024
Google search engine
HomeLanguagesJavaConvert Date to XMLGregorianCalendar in Java

Convert Date to XMLGregorianCalendar in Java

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 necessary 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 XMLGregorian 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

 

RELATED ARTICLES

Most Popular

Recent Comments