You don’t need an XMLGregorianCalender
. It will not, cannot give you what you ask for. Instead you need a LocalDate
and a DateTimeFormatter
:
DateTimeFormatter italianDateFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.ITALIAN);
LocalDate date = LocalDate.now(ZoneId.of("Europe/Rome"));
String formattedDate = date.format(italianDateFormatter);
System.out.println(formattedDate);
When I ran this code today, the output was:
21/01/19
The difference from what you ask for is the two digit year, 19
. If instead of FormatStyle.SHORT
we use FormatStyle.MEDIUM
, we get four digit year, but the month as a three letter abbreviaiton:
21-gen-2019
The advantage is that the code lends itself very well to internationalization: you just need to change the locale to get proper code for some other language and country. If you do need 21/01/2019
(with four digit year), specify the format explicitly using a pattern:
DateTimeFormatter italianDateFormatter
= DateTimeFormatter.ofPattern("dd/MM/uuuu");
21/01/2019
What’s wrong with using XMLGregorianCalendar
?
When you call System.out.println(xmlDate)
, you are implicitly calling toString
on your XMLGregorianCalendar
. When it hasn’t got time and zone offset, toString
always generates yyyy-MM-dd
format, there is no way you can change that. On the other hand you can have any format you like in a String
. Next obstacle is, there is no formatter that can format an XMLGregorianCalendar
directly. You would need to convert to a different type, like ZonedDateTime
, for example, first. Since you only want the date, neither the time of day nor the time zone, it’s simpler and easier to start out from LocalDate
from the start. Not least for those reading and maintaining your code after you.
Your question mentions java.util.Date
and your code uses GregorianCalendar
too. Both of those classes are poorly designed and long outdated, fully replaced by java.time, the modern Java date and time API. So I suggest you don’t use them.
Link
Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API.