I have a code snippet that will convert Date
to XMLGregorianCalendar
, but after seeing the results dates are different. Not sure why change in dates after conversions.
Code:
public void getDate() throws ParseException {
Date current = null;
String str = "1980-10-26";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date current1 = format.parse(str);
XMLGregorianCalendar xmlCalendar = null;
xmlCalendar = Utility.convertDateToXMLGreCal(current1);
System.out.println("xmlCalendar: "+xmlCalendar);
current = Utility.convertXMLGreClndrToDate(xmlCalendar);
System.out.println("current1: "+current.toString());
}
public static XMLGregorianCalendar convertDateToXMLGreCal(final Date date){
TimeZone zone = TimeZone.getTimeZone("UTC");
GregorianCalendar gregoClndr = new GregorianCalendar(zone);
gregoClndr.setTime(date);
XMLGregorianCalendar xmlGreClndr = null;
try {
final DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
xmlGreClndr = dataTypeFactory.newXMLGregorianCalendar(gregoClndr);
} catch (DatatypeConfigurationException e) {
}
return xmlGreClndr;
}
*
Results:
xmlCalendar: 1980-10-25T18:30:00.000Z current1: Sun Oct 26 00:00:00 IST 1980
I am expecting xmlCalendar
as 1980-10-26T00:00:00.000Z
.
Can someone let me know how to do that?
The problem is that you're not specifying a time zone in your DateFormat
- so the system default time zone is being used. The result is midnight in your local time zone (IST) but in the XMLGregorianCalendar
, it's being rendered in UTC.
The simplest way to fix this is to specify UTC as the time zone in your DateFormat
:
format.setTimeZone(TimeZone.getTimeZone("UTC"));
That way each date will be parsed as midnight on the start of that "UTC day" which sounds like it's what you were expecting.
See more on this question at Stackoverflow