Friday, February 29, 2008

Coverting Date to XMLGregorianCalendar format in java

private XMLGregorianCalendar Date2XMLDate(Date d)
throws DatatypeConfigurationException {


Calendar c = new GregorianCalendar();

c.setTime(d);
int month = c.get(Calendar.MONTH)+1;
int day = c.get(Calendar.DAY_OF_MONTH);
int year = c.get(Calendar.YEAR);
DatatypeFactory df = DatatypeFactory.newInstance();

XMLGregorianCalendar x = df.newXMLGregorianCalendarDate(year, month, day, c.getTimeZone().getOffset(d.getTime())/(60*60*1000));

return x;
}

1 comment:

Gabou said...

I would go on


/**
* Transform a date in a long to a GregorianCalendar
*
* @param date
* @return
*/
public static XMLGregorianCalendar long2Gregorian(long date) {
DatatypeFactory dataTypeFactory;
try {
dataTypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new RuntimeException(e);
}
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(date);
return dataTypeFactory.newXMLGregorianCalendar(gc);
}

/**
* Transform a date in Date to XMLGregorianCalendar
*/
public static XMLGregorianCalendar date2Gregorian(Date date) {
return long2Gregorian(date.getTime());
}