the Date Thu Sep 27 00:00:00 CEST 2018
becomes
2018-09-26T22:00:00.000Z
when converted in XMLGregorianCalendar
by this method:
public static XMLGregorianCalendar dateToXMLGregorianCalendar(Date date) throws DatatypeConfigurationException{
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
}
How can I avoid this date change?
Tnx
It’s a question with a number of possible answers depending on your circumstances and exact requirements. I am assuming that you are asking for an
XMLGregorianCalendar
because you are going to use it in an XML document where itstoXMLFormat
method produces the syntax you need.Try if a LocalDate works
This outputs:
If what you need to put into your XML document is a date, not a date and time and UTC offset, this would be the logical solution. The above is a valid date format in XML (check the links at the bottom). Whether the receiver of your XML document accepts it I cannot tell. I’d find out if that were me.
The method in your question accepts a
Date
argument. TheDate
class is long outdated and has design problems, so avoid it if you can. If you cannot avoid it, convert it toLocalDate
like this:Please use your desired time zone where I put Europe/Rome since it is never the same date in all time zones. The correct time zone is what controls whether you get September 26 or 27.
Use OffsetDateTime
This is almost the syntax you also get from
XMLGregorianCalendar
(XMLGregorianCalendar
could produce it too if you wanted). Seconds and milliseconds are not included. Again, check if it’s OK. If it isn’t, format yourOffsetDateTime
into aString
for your XML:This follows the syntax you got from
XMLGregorianCalendar
in your question exactly, only the date and time have not been changed. Again if you cannot avoid accepting an old-fashionedDate
, convert:If you do need an XMLGregorianCalendar
The specification of time zone controls the offset and thereby also the date and time produced.
Links