1

I convert from String date to XMLGregorianCalendar

public static void convertStringToXMLDate(String dateString) {
    Date dob=null;
    DateFormat df=new SimpleDateFormat("yyyyMMdd");
    try {
        dob=df.parse( "20140210" );
    } catch (ParseException e) {
        e.printStackTrace();
    }
    GregorianCalendar cal = new GregorianCalendar();

    cal.setTime(dob);
    XMLGregorianCalendar xmlDate3;
    try {
        xmlDate3 = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH),dob.getHours(),dob.getMinutes(),dob.getSeconds(),DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
        System.out.println(xmlDate3);
    } catch (DatatypeConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

This code print xmlDate3 = 2014-02-10T00:00:00.

How can I format this to 20140210 or 2014/02/10 in XMLGregorianCalendar

Jerry
  • 185
  • 1
  • 6
  • 18
  • This question is not a duplicate of http://stackoverflow.com/questions/835889/java-util-date-to-xmlgregoriancalendar, since OP already know how to convert `Date` to `XMLGregorianCalendar`. – Andreas Dec 07 '15 at 04:00

1 Answers1

3

You cannot. The XMLGregorianCalendar is a (from javadoc):

Representation for W3C XML Schema 1.0 date/time datatypes [...] normatively defined in W3C XML Schema 1.0 Part 2, Section 3.2.7-14.

As you can see, the referenced normative definition of a dateTime is:

3.2.7.1 Lexical representation

The ·lexical space· of dateTime consists of finite-length sequences of characters of the form: '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?

The only potential choice in format is between "Lexical representation" and "Canonical representation". Formatting like you show (20140210 and 2014/02/10) is not valid for an XML Schema defined dateTime value.


Now, if you actually wanted an XML date value, not a dateTime, then you should call newXMLGregorianCalendarDate(int year, int month, int day, int timezone) instead of newXMLGregorianCalendar(int year, int month, int day, int hour, int minute, int second, int millisecond, int timezone).

The output will then be:

2014-02-10
Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247