Convert to XMLGregorianCalendar with date only (time set to zero). - Java XML

Java examples for XML:XML Calendar

Description

Convert to XMLGregorianCalendar with date only (time set to zero).

Demo Code

/*//  ww w .ja v  a  2s. c  o m
 * Copyright 2012 Ixonos Plc, Finland. All rights reserved.
 * Copyright 2012 Arcusys Oy, Finland. All rights reserved.
 *
 * This file is part of Kohti kumppanuutta.
 *
 * This file is licensed under GNU LGPL version 3.
 * Please see the 'license.txt' file in the root directory of the package you received.
 * If you did not receive a license, please contact the copyright holders (http://www.ixonos.com/, http://www.arcusys.fi/).
 * 
 */
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class Main{
    public static void main(String[] argv) throws Exception{
        Date date = new Date();
        System.out.println(getXmlDate(date));
    }
    /**
     * Convert to XMLGregorianCalendar with date only (time set to zero).
     * 
     * @param date
     * @return XMLGregorianCalendar
     */
    public static XMLGregorianCalendar getXmlDate(final Date date) {
        return getXmlCalendar(date, new SetDateOnlyCalendar());
    }
    private static XMLGregorianCalendar getXmlCalendar(final Date date,
            final SetCalendar setCalendar) {
        if (date == null) {
            return null;
        }
        try {
            final GregorianCalendar calendar = (GregorianCalendar) GregorianCalendar
                    .getInstance();
            calendar.setTime(date);
            setCalendar.setCalendar(calendar);
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(
                    calendar);
        } catch (DatatypeConfigurationException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials