I assume that your desired result is an XMLGregorianCalendar
like 2018-06-30T00:00:00.000+02:00
(at least that’s the result I get when running your code on my computer (it works)).
This answer further assumes that you are getting your java.sql.Date
from an SQL database and that you want your XMLGregorianCalendar
for the String
that you get from its toXMLFormat
method. If so, I suggest that you neither need java.sql.Date
nor XMLGregorianCalendar
(that’s right).
To get your date from your result set:
LocalDate invReceivedDate = yourResultSet.getObject("inv_receive_date", LocalDate.class);
I haven’t tested the code, and you should of course substitute the correct column label instead of inv_receive_date
. If using JPA a modern version can give you a LocalDate
object too.
To get your string for XML:
OffsetDateTime date = invReceivedDate.atStartOfDay(ZoneId.systemDefault())
.toOffsetDateTime();
System.out.println(date.toString());
In my test run this printed
2018-06-30T00:00+02:00
If you compare with the string I got from date.toXMLFormat()
before, you will notice that the seconds and fraction of second are not printed. This is probably OK. The format is ISO 8601, and according to that standard seconds and fraction of second are optional, so leaving them out when they are 0 should work. If you have a special requirement to include them, you may use
DateTimeFormatter formatterForXml
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxxx");
System.out.println(date.format(formatterForXml));
This time the output is
2018-06-30T00:00:00.000+02:00
So exactly as from date.toXMLFormat()
before. It’s also possible that you only need the date without time-of-day and UTC offset. If so, it still simpler:
System.out.println(invReceivedDate.toString());
Output:
2018-06-30
Why? Not just because it works. java.sql.Date
is long outdated and poorly designed, so don’t use it. Instead I am using LocalDate
from java.time, the modern Java date and time API. The modern API is so much nicer to work with.
Link: Oracle tutorial: Date Time explaining how to use java.time
.