What is the best way to convert XMLGregorianCalendar objects to \'MM/dd/yyyy hh:mm\' String?
This example convert XMLGregorianCalendar to date
XMLGregorianCalendar xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
Date date = xmlCalendar.toGregorianCalendar().getTime();
This example convert date to string
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm");
String dateStr = df.format(GregorianCalendar.getInstance().getTime());
You can use toGregorianCalendar() method for this.
E.g.:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
String date = sdf.format(xmlGregorianCalendar.toGregorianCalendar().getTime());
In case, you need to convert that calendar to different TimeZone and Locale, use toGregorianCalendar(TimeZone timezone, Locale aLocale, XMLGregorianCalendar defaults)
Please check this static utility. You just mentioned a pattern like "ddMMyy" or "HHmm" or what ever you want.. this will work wonderfully.
public static String getDateTime(XMLGregorianCalendar gDate, String pattern){
return Optional.ofNullable(gDate)
.map(gdate -> {
Calendar calendar = gDate.toGregorianCalendar();
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.setTimeZone(calendar.getTimeZone());
return formatter.format(calendar.getTime());
})
.orElse(null);
}
First use XMLGregorianCalendar#toGregorianCalendar() to get a java.util.Calendar instance out of it.
Calendar calendar = xmlGregorianCalendar.toGregorianCalendar();
From that step on, it's all obvious with a little help of SimpleDateFormat the usual way.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm");
formatter.setTimeZone(calendar.getTimeZone());
String dateString = formatter.format(calendar.getTime());
I only wonder if you don't actually want to use HH
instead of hh
as you aren't formatting the am/pm marker anywhere.
This is an example you are looking for:
XMLGregorianCalendar date = ...; // initialization is out of scope for this example
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
GregorianCalendar gc = date.toGregorianCalendar();
String formatted_string = sdf.format(gc.getTime());