public class Main {
public static void main(String[] args) throws IOException, ParseException, DatatypeConfigurationException {
DateFormat format = new SimpleDateFormat("YYYY-MM-DD");
Date date = format.parse("2022-04-13T09:54:54-04:00");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(xmlGregCal);
// Expected is 2022-04-13 in XMLGregorianCalendar value
// But getting 2021-12-26T00:00:00.000+11:00
}
}
Expected is 2022-04-13 in XMLGregorianCalendar value. But getting 2021-12-26T00:00:00.000+11:00. Can some expert please help here?
You have multiple problems.
Parse your input as a
OffsetDateTime
object. Your input text complies with the ISO 8601 standard format used by default in java.time. So no need to specify a formatting pattern.You have no need to further involve more legacy classes such as
GregorianCalendar
orXMLGregorianCalendar
. Job done. There is no point to using or studying these classes. Their functionality has been entirely replaced by java.time.You can generate text in standard ISO 8601 format by calling
OffsetDate#toString
.See this code run live at Ideone.com.
You said:
Date-time objects do not have a “format”. Text has a format.
GregorianCalendar
,XMLGregorianCalendar
, andOffsetDateTime
are not text.