What is the best way to convert XMLGregorianCalendar objects to 'MM/dd/yyyy hh:mm' String?
The simplest way to format XMLGregorianCalendar is to first convert it to the Date object, and format the Date to String. XMLGregorianCalendar xCal = ..; //Create instance Date date = xCal. toGregorianCalendar(). getTime(); DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a z"); String formattedString = df.
Since java. util. Date is the most common way to deal with Java date and time, we always need to convert the instance of XMLGregorianCalendar to the Java Date instance. Using the Java API, we can easily convert XMLGregorianCalendar to XMLGregorianCalendar Date and Date in Java.
The XML Schema standard defines clear rules for specifying dates in XML format. In order to use this format, the Java class XMLGregorianCalendar, introduced in Java 1.5, is a representation of the W3C XML Schema 1.0 date/time datatypes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With