Search code examples
javasimpledateformatgregorian-calendar

Format XMLGregorianCalendar


Below is my code

GregorianCalendar gregory=new GregorianCalendar();
gregory.setTime(new Date());
XMLGregorianCalendar xmlGregorianCalendar=DatatypeFactory.newInstance().newXMLGregorianCalendar(gregory);
System.out.println(xmlGregorianCalendar.toString());

When I am printing SOP in last line of above code am getting output like

2016-07-28T15:25:47.064+05:30

But Iam trying to get output as

2016-07-28+05:30

I have tried different formatters but no luck.

Any suggestions will be much helpfull for me

Atleast can we get this format using SimpleDateFormat?

By using simpledateformat iam able to get "2016-07-29+0530". Can you please let me know if we can bring ":" in between "05" and "30". My code below

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddZ");

In Java version 7 and 8 it is possible to get by using below

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddXXX");

but not sure in java 6 version


Solution

  • The easiest would be to rebuild the JDK7 functionality. You have to know that the new XXX calculation is based on the already available fields of the Calendar class. They take the Calendar.ZONE_OFFSET and the Calendar.DST_OFFSET and go from there like this:

        int totalOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
    
        StringBuilder sb = new StringBuilder();
    
        //handle zero offset
        if (totalOffset == 0) {
            sb.append('Z');
        }
    
        //convert to minutes because timezones are minute based
        totalOffset = totalOffset / 60000;
        char prefix = '-';
        if (totalOffset >= 0) {
            prefix = '+';
        }
        sb.append(prefix);
    
        //if negative offset, invert now
        totalOffset = Math.abs(totalOffset);
    
        sb.append(String.format("%02d", (totalOffset / 60)));
        sb.append(':');
        sb.append(String.format("%02d", (totalOffset % 60)));
    
        System.out.println(sb.toString());
    

    I hope this snippet helps you to go from there.