Saturday, November 10, 2012

ISO8601 UTC with XStream

I need ISO8601 conversion with XStream for UTC (GMT/Zulu) time. Originally I went with ISO8601DateConverter which comes with XStream and uses Joda. However I found that it read in UTC (GMT/Zulu) time but wrote back out local time.

To fix this I wrote my own converter using JAXB in the JDK, and dropped the Joda runtime dependency from my project.

I unit tested full roundtrip with "2012-10-22T12:34:56Z". The original converter parsed correctly but serialized as "2012-10-22T07:34:56-05:00". My converter serializes as the input string.

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

import java.util.Date;
import java.util.GregorianCalendar;

import static java.util.TimeZone.getTimeZone;
import static javax.xml.bind.DatatypeConverter.parseDateTime;
import static javax.xml.bind.DatatypeConverter.printDateTime;

/**
 * {@code UTCConverter} converts {@code java.util.Date} objects in ISO8601
 * format for UTC without milliseconds.
 *
 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
 */
public final class UTCConverter
        extends AbstractSingleValueConverter {
    @Override
    public boolean canConvert(final Class type) {
        return Date.class.isAssignableFrom(type);
    }

    @Override
    public String toString(final Object obj) {
        final GregorianCalendar gmt = new GregorianCalendar(getTimeZone("GMT"));
        gmt.setTime(Date.class.cast(obj));
        return printDateTime(gmt);
    }

    @Override
    public Object fromString(final String str) {
        return parseDateTime(str).getTime();
    }
}
Post a Comment