i have a date String which looks just like this.
2017-12-06T17:39:00Z
What i would like to do is to convert this String to XMLGregorianCalendar but using the same format.
What i do at the moment is:
String choosenDate = 2017-12-06T17:39:00Z;
GregorianCalendar c = new GregorianCalendar();
DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
TemporalAccessor accessor = timeFormatter.parse(dateChoisie);
Date date = Date.from(Instant.from(accessor));
c.setTime(date);
System.err.println("choosenDate: " + dateChoisie);
System.err.println("date : " + date);
XMLGregorianCalendar dateXMLGreg = null;
try
{
dateXMLGreg = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
System.err.println("dateXMLGreg: " + dateXMLGreg);
}
catch (DatatypeConfigurationException e)
{
messages.addMessage(new MessageBuilder().error().code("webservice.failure").build());
}
which gives me the following output:
10:47:45,957 ERROR [stderr] (default task-47) choosenDate: 2017-12-06T17:39:03Z
10:47:45,957 ERROR [stderr] (default task-47) date : Wed Dec 06 18:39:03 CET 2017
10:47:45,958 ERROR [stderr] (default task-47) dateXMLGreg: 2017-12-06T18:39:03.000+01:00
So how can i do so i have my XMLGregorianCalendar dateXMLGreg to look like:
2017-12-06T17:39:03Z
This is easier than you think.
This prints
newXMLGregorianCalendar
has an overloaded version that accepts a string — your string — as argument. I trust you to add try/catch as in your question.Edit: your
XMLGregorianCalendar
will have its milliseconds set toDatatypeConstants.FIELD_UNDEFINED
. This needs to be so to avoid printing the milliseconds as part of the result fromtoString()
(which gets implicitly called when you print theXMLGregorianCalendar
).One more edit: As Basil Bourque correctly said in a comment, depending on what you need your
XMLGregorianCalendar
for, you may use and even benefit from using a class fromjava.time
, the modern Java date and time API, instead. For example:This gives the exact same output as above,
2017-12-06T17:39:00Z
. TheInstant
class will work only if the offset is alwaysZ
, which it probably is since this was what you asked to have back. The potential advantages ofjava.time
include (1) the API is generally much nicer to work with (2) in case you need some further date-time operations, the modern API offers a wealth of them. If the offset may vary, you may experiment withOffsetDateTime
, but this is a longer story that I will leave for some other question.