tl;dr
myJavaUtilDate.toInstant()
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.toString()
2017-01-23
Details
No such thing as an XML date
. Perhaps you mean the date-time formats defined in XML Schema by the W3C. These formats are amongst those defined by the ISO 8601 standard, and are used by the java.time classes by default when parsing/generating strings.
Your Question is confused, asking for a String yet showing code that generates an XMLGregorianCalendar
object. Date-time objects such as XMLGregorianCalendar
do not have a format. Such date-time objects store information, not text. You may ask such objects to generate a String object whose text represents the value within the object. But the String and the date-time object are entirely distinct and separate.
Avoid legacy date-time classes such as java.util.Date
, Calendar
, etc. These are now legacy, supplanted by the java.time classes.
The equivalent of java.util.Date
is Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). You may convert by calling new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant();
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You want to work with only the date portion, without a time-of-day. So extract a LocalDate
.
LocalDate ld = zdt.toLocalDate();
Your desired format complies with the standard ISO 8601 formats for date-time text. The java.time classes use the standard formats by default. So no need to specify a formatting pattern.
String output = ld.toString() ;
2017-01-23
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.