Reputation: 2103
I have an instance of XMLGregorianCalendar
with date format as
yyyy-MM-dd'T'HH:mm:ss
I need an instance of an XMLGregorianCalendar
with
yyyy-MM-dd':'HH:mm:ss
date format. Is it possible?
I need to set this date in XML using JAXB where schema mandates that the field be XMLGregorianCalendar
.
Upvotes: 1
Views: 897
Reputation: 86149
No, it is not possible. The whole point in XMLGregorianCalendar
is to provide dates and times in a format required by XML, and the format you are asking about is not allowed in XML. So what you are asking for is prevented on purpose.
If your requirement is an XMLGregorianCalendar
, then you will have to live with the format printed from its toString
and toXMLFormat
methods (the two return the identical strings). I also don’t see why you should not be happy with that. This format fulfils the XML specification.
PS While toString()
and toXMLFormat()
return strings in XML format, i consider it wrong to say that the XMLGregorianCalendar
has got this format. Its internal representation is quite different (and nothing we should care about). I consider it more correct to say that an XMLGregorianCalndar
cannot have a format.
Link: An answer of mine treating more thoroughly why you can have no date-time object with a format. I am using Date
as an example, but what I write is fully valid for XMLGregorianCalendar
too, and I do mention XMLGregorianCalendar
at the end.
Upvotes: 0
Reputation: 78965
Convert the object of XMLGregorianCalendar
to an object of ZonedDateTime
which you can format in the desired format using DateTimeFormatter
.
Demo:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Main {
public static void main(String[] args) throws DatatypeConfigurationException {
String givenDateTimeString = "2020-11-08T13:05:46";
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(givenDateTimeString);
System.out.println(xmlGregorianCalendar);
ZonedDateTime zdt = xmlGregorianCalendar.toGregorianCalendar().toZonedDateTime();
String formatted = DateTimeFormatter.ofPattern("uuuu-MM-dd':'HH:mm:ss", Locale.ENGLISH).format(zdt);
System.out.println(formatted);
}
}
Output:
2020-11-08T13:05:46
2020-11-08:13:05:46
Now, you can use the string, formatted
in your XML.
Note: A date-time object is supposed to store the information about date, time, timezone etc., not about the formatting. You can format a date-time object into a String
with the pattern of your choice using date-time formatting API.
java.time.format.DateTimeFormatter
, java.time.format.DateTimeFormatterBuilder
etc.) for the modern date-time types is in the package, java.time.format
.java.text.SimpleDateFormat
, java.text.DateFormat
etc.) for the legacy date-time types is in the package, java.text
.Upvotes: 1