Reputation: 35
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?
Upvotes: 0
Views: 292
Reputation: 338181
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.
OffsetDateTime odt = OffsetDateTime.parse( "2022-04-13T09:54:54-04:00" ) ;
You have no need to further involve more legacy classes such as GregorianCalendar
or XMLGregorianCalendar
. 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
.
String output = odt.toString() ;
See this code run live at Ideone.com.
2022-04-13T09:54:54-04:00
You said:
change the format to XMLGregorianCalendar
Date-time objects do not have a “format”. Text has a format. GregorianCalendar
, XMLGregorianCalendar
, and OffsetDateTime
are not text.
Upvotes: 1