The answer by Arvind Kumar Avinash is good and correct. There are other ways to obtain the same, so as a supplement I am presenting a couple.
Edit: A simpler and shorter variant of the code by Arvind Kumar Avinash:
XMLGregorianCalendar xmlCal
= DatatypeFactory.newInstance().newXMLGregorianCalendar();
xmlCal.setYear(2021);
System.out.println(xmlCal);
Output:
2021
The no-arg newXMLGregorianCalendar()
gives us an XMLGregorianCalendar
with all fields undefined or null
. Set the year, and we’re done.
You may also create your desired XMLGregorianCalendar
fully complete directly from a factory method call. Here’s a longish variant:
XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
.newXMLGregorianCalendarDate(2021, DatatypeConstants.FIELD_UNDEFINED,
DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
The result is the same as before. The fields that I set undefined are month, day of month and UTC offset (called timezone with XMLGregorianCalendar
).
A much shorter variant is:
XMLGregorianCalendar xmlCal
= DatatypeFactory.newInstance().newXMLGregorianCalendar("2021");
Output is still the desired:
2021
Just as you want an XMLGregorianCalendar
for the purpose of producing a specific string, the XMLGregorianCalendar
can also be constructed from the string you want.
In case you had your year in an int
, you may convert first:
int year = 2021;
XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(String.valueOf(year));
It may feel like a waste to convert your int
to a String
only to have it parsed again. You decide.
Which way to prefer? It’s a matter of taste.
java.time.Year
As an aside, only if your class requires an XMLGregorianCalendar
, use that class. For all other purposes I recommend the Year
class:
Year year = Year.of(2021);
System.out.println(year);
2021