Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract one day in XMLGregorianCalendar

Tags:

java

datetime

How to subtract one day in XMLGregorianCalendar? Also while subtracting how to cope up with following problems :

  • it does not goes to a negative value in case of first day of the month
  • in case of 1st Jan of a year, where it needs to go back to a previus year

and other similar stuffs.

Please do not suggest to use any other library like Joda-Time. I know they are great, but I need to get this done using XMLGregorianCalendar only.

Thanks

like image 308
sam100rav Avatar asked Dec 06 '22 19:12

sam100rav


1 Answers

Just convert to a normal GregorianCalendar, do the arithmetic there, then convert back:

GregorianCalendar calendar = xmlCalendar.toGregorianCalendar();
calendar.add(Calendar.DAY_OF_MONTH, -1);
xmlCalendar = datatypeFactory.newXMLGregorianCalendar(calendar);

(This assumes you already have a DatatypeFactory of course. You can always call DatatypeFactory.newInstance() if necessary.)

like image 68
Jon Skeet Avatar answered Dec 22 '22 14:12

Jon Skeet