Nare Hopane
Nare Hopane

Reputation: 51

changing XMLgregorianCalender default format to "yyyyMMdd"

need assistant, i need to change the default format (2017-01-18) for XMLGregorianCalendar to example "20170118" , i have tried a lot of examples through here but its not helping

private static SimpleDateFormat formats = new SimpleDateFormat("yyyyMMdd");

public static XMLGregorianCalendar unmarshal(String value) {
    try {
        return toXMLGregorianCalendar(formats.parse(value));
    } catch ( ParseException e ) {
        e.printStackTrace();
        return null;
    }
}

Upvotes: 0

Views: 223

Answers (1)

Mincong Huang
Mincong Huang

Reputation: 5552

I'm afraid you cannot do that. If you take a look into the class XMLGregorianCalendar, you'll find that the toString() method just call the toXMLFormat() and the toXMLFormat() doesn't provide any possibility for format customization.

public String toXMLFormat() {

    QName typekind = getXMLSchemaType();

    String formatString = null;
    // Fix 4971612: invalid SCCS macro substitution in data string
    //   no %{alpha}% to avoid SCCS macro substitution
    if (typekind == DatatypeConstants.DATETIME) {
        formatString = "%Y-%M-%DT%h:%m:%s" + "%z";
    } else if (typekind == DatatypeConstants.DATE) {
        formatString = "%Y-%M-%D" + "%z";
    } else if (typekind == DatatypeConstants.TIME) {
        formatString = "%h:%m:%s" + "%z";
    } else if (typekind == DatatypeConstants.GMONTH) {
        formatString = "--%M" + "%z";
    } else if (typekind == DatatypeConstants.GDAY) {
        formatString = "---%D" + "%z";
    } else if (typekind == DatatypeConstants.GYEAR) {
        formatString = "%Y" + "%z";
    } else if (typekind == DatatypeConstants.GYEARMONTH) {
        formatString = "%Y-%M" + "%z";
    } else if (typekind == DatatypeConstants.GMONTHDAY) {
        formatString = "--%M-%D" + "%z";
    }
    return format(formatString);
}

Is there any work-around solution?

Well, if you just want to get a string of type yyyyMMdd from a XMLGregorianCalendar object, you can do:

XMLGregorianCalendar c = YourCalendarHelper.unmarshal("2017-01-18");
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String str = format.format(c.toGregorianCalendar().getTime());

System.out.println(str);  // 20170118

By the way, if an exception raised during the conversion, DO NOT catch it unless you know you're 100% sure how to handle it. Throw it through the method declaration, so that the caller this method is aware of the potential failure.

Upvotes: 1

Related Questions