Friday, February 25, 2011

XmlGregorianCalendar, what you get isn't what you want

Question: What you get when you do such thing?

variable calendar is an instance of XMLGregorianCalendar (year=2011,month=2,day=1, hour, minute and seconds are not set).


Calendar result = Calendar.getInstance();
result.clear();
result.set(calendar.getYear(), calendar.getMonth() - 1, calendar.getDay(), calendar.getHour(), calendar.getMinute(),calendar.getSecond());
result.set(Calendar.MILLISECOND, calendar.getMillisecond());


You might be thinking that you will get:

Year=2011
Month=1 (February)
Day=1
Hour, minute, seconds = 0

Be aware of doing this! While some field in gregorian calendar is not set then it's value is "-2147483648"

So, If you do such a conversion then you endup in 247120 years B.C.E ;-)


Solution:

use method:
calendar.toGregorianCalendar();


Implementation of this method:

if(month != -2147483648)
gregoriancalendar.set(2, month - 1);
if(day != -2147483648)
gregoriancalendar.set(5, day);
if(hour != -2147483648)
gregoriancalendar.set(11, hour);
if(minute != -2147483648)
gregoriancalendar.set(12, minute);
if(second != -2147483648)
gregoriancalendar.set(13, second);
if(fractionalSecond != null)
gregoriancalendar.set(14, getMillisecond());
return gregoriancalendar;


It's a kind of magic :-)

No comments:

Post a Comment