Required XMLGregorianCalendar date and time in e.g. 2012 06 08T08:16:43+00:00 format (according to the W3C guidelines)

Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String formattedDate = sdf.format(d); //yyyy-MM-dd HH:mm:ss
convertStringToXmlGregorian(formattedDate);

public XMLGregorianCalendar convertStringToXmlGregorian(String dateString) {
    XMLGregorianCalendar xmlCal = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
    try {
        Date date = sdf.parse(dateString);
        GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
        gc.setTime(date);
        try {
            xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
        } catch (DatatypeConfigurationException e) {
            e.printStackTrace();
        }
    } catch (ParseException e) {
        // Optimize exception handling
        System.out.print(e.getMessage());
        return null;
    }
    return xmlCal;
}

1. I GET folowing output: 2014-06-12T20:19:05.000+05:30 1. i want xmlCal to return date in as 2014-06-12T08:16:43+00:00

Jon Skeet
people
quotationmark

Your GregorianCalendar is in your system time zone. All you need is:

TimeZone utc = TimeZone.getTimeZone("Etc/UTC");
GregorianCalendar gc = new GregorianCalendar(utc);

Having said that, it's not clear why you're converting a date to a string, then parsing it, then reformatting it. Also, you're formatting with a T in the pattern, and then parsing it without a T in the pattern - that's not going to work. I suspect the code you've given isn't the code you've actually got.

Are you always trying to create an XMLGregorianCalendar for the current date and time? Why not just skip the format/parse part?

(I'd also strongly advise against the exception handling code you've got.)

people

See more on this question at Stackoverflow