Tuesday, December 09, 2008

XMLGregorianCalendar, DateTime etc

If you are interested in creating a new instance of XMLGregorianCalendar, then the following code should work for the current time and timezone.

==============================================
DatatypeFactory dtf = DatatypeFactory.newInstance();
XMLGregorianCalendar xgc = dtf.newXMLGregorianCalendar();

Calendar cal = Calendar.getInstance();
xgc.setYear(cal.get(Calendar.YEAR));
xgc.setDay(cal.get(Calendar.DAY_OF_MONTH));
xgc.setMonth(cal.get(Calendar.MONTH)+ 1);
xgc.setHour(cal.get(Calendar.HOUR_OF_DAY));
xgc.setMinute(cal.get(Calendar.MINUTE));
xgc.setSecond(cal.get(Calendar.SECOND));
xgc.setMillisecond(cal.get(Calendar.MILLISECOND));

// Calendar ZONE_OFFSET and DST_OFFSET fields are in milliseconds.
int offsetInMinutes = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000);
xgc.setTimezone(offsetInMinutes);
=================================================

Simpler option:

=================================================
GregorianCalendar gc = new GregorianCalendar();
DatatypeFactory dtf = DatatypeFactory.newInstance();
XMLGregorianCalendar xgc = dtf.newXMLGregorianCalendar(gc);
==================================================

No comments: