Convert Date into XMLGregorianCalendar. - Java XML

Java examples for XML:XML Calendar

Description

Convert Date into XMLGregorianCalendar.

Demo Code


//package com.java2s;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        Date date = new Date();
        System.out.println(convert2XmlDateWithoutTimezone(date));
    }//from  ww w  .j a v a  2 s .  c o m

    /**
     * Convert Date into XMLGregorianCalendar. We want, that method
     * {@link XMLGregorianCalendar#toXMLFormat} produce date format
     * 'yyyy-MM-dd'. To accomplish this, it is necessery to set TimeZone value
     * of the {@link XMLGregorianCalendar} to
     * {@link DatatypeConstants#FIELD_UNDEFINED} If TimeZone would be set to 0,
     * output would be yyyy-MM-ddZ, which is also correct but more applications
     * outside will be able process the first format.
     *
     * @param date
     *            the date
     * @return representation of the date (no time set)
     */
    public static XMLGregorianCalendar convert2XmlDateWithoutTimezone(
            Date date) {
        if (date == null) {
            throw new IllegalArgumentException(
                    "Argument 'Date date' is null!");
        }

        GregorianCalendar utilGregorianCalendar = new GregorianCalendar();
        utilGregorianCalendar.setTimeInMillis(date.getTime());
        try {
            return DatatypeFactory.newInstance()
                    .newXMLGregorianCalendarDate(
                            utilGregorianCalendar.get(Calendar.YEAR),
                            utilGregorianCalendar.get(Calendar.MONTH) + 1,
                            utilGregorianCalendar
                                    .get(Calendar.DAY_OF_MONTH),
                            DatatypeConstants.FIELD_UNDEFINED);
        } catch (DatatypeConfigurationException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials