Skip to content

Instantly share code, notes, and snippets.

@compwron
Created September 19, 2013 02:19
Show Gist options
  • Save compwron/6618348 to your computer and use it in GitHub Desktop.
Save compwron/6618348 to your computer and use it in GitHub Desktop.
XMLGregorianCalendar from GregorianCalendar
import org.junit.Test;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static junit.framework.Assert.assertEquals;
public class MessTest {
@Test
public void shouldTranslateValidCalendar() throws DatatypeConfigurationException {
GregorianCalendar cal = new GregorianCalendar(2013, 1, 1, 1, 1, 1);
XMLGregorianCalendar xmlCal = new Mess().translateToXMLCal(cal);
verifyDateSameness(cal, xmlCal);
}
private void verifyDateSameness(GregorianCalendar cal, XMLGregorianCalendar xmlCal) {
assertEquals(xmlCal.toString(), xmlCalFormatter(cal));
assertEquals(xmlCal.getYear(), cal.get(Calendar.YEAR));
assertEquals(xmlCal.getMonth(), cal.get(Calendar.MONTH) + 1); // GregorianCalendar starts at 0 and XMLGregorianCalendar starts at 1
assertEquals(xmlCal.getDay(), cal.get(Calendar.DAY_OF_MONTH));
assertEquals(xmlCal.getHour(), cal.get(Calendar.HOUR));
assertEquals(xmlCal.getMinute(), cal.get(Calendar.MINUTE));
assertEquals(xmlCal.getSecond(), cal.get(Calendar.SECOND));
assertEquals(xmlCal.getMillisecond(), cal.get(Calendar.MILLISECOND));
assertEquals(xmlCal.getTimezone(), cal.get(Calendar.ZONE_OFFSET) / 60000); // Not sure why zone offset requires this translation
}
private String xmlCalFormatter(GregorianCalendar cal) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String timeWithoutColon = fmt.format(cal.getTime());
int afterMilliseconds = 26;
return timeWithoutColon.substring(0, afterMilliseconds) + ":" + timeWithoutColon.substring(afterMilliseconds, timeWithoutColon.length());
}
public class Mess {
public XMLGregorianCalendar translateToXMLCal(GregorianCalendar cal) throws DatatypeConfigurationException {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment