I am getting a Date object, which i need to convert to XMLGregorian Calendar specific format
I tried below ways
String formattedDate = sdf.format(categoryData.getBulkCollectionTime()); //yyyy-MM-dd HH:mm:ss
XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(formattedDate);
dataListType.setTimestamp(xmlCal);
I am getting an exception, for sure I am doing wrong here. But I want to format the Date object into specified format, which is done by sdf.format perfectly.
But how do I create the XMLGregorianCalendar object for the same (from formattedDate)?
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.
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.
2. XMLGregorianCalendar. 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.
Create a new XMLGregorianCalendar by parsing the String as a lexical representation. Create a Java representation of XML Schema builtin datatype date or g* . Create a Java instance of XML Schema builtin datatype time. Create a Java instance of XML Schema builtin datatype time .
You should fixed your date format:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = sdf.format(new Date());
XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(date);
You can do it by the date object itself:
String formattedDate = sdf.format(categoryData.getBulkCollectionTime()); //yyyy-MM-dd HH:mm:ss
convertStringToXmlGregorian(formattedDate);
public XMLGregorianCalendar convertStringToXmlGregorian(String dateString)
{
try {
Date date = sdf.parse(dateString);
GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.setTime(date);
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
} catch (ParseException e) {
// Optimize exception handling
System.out.print(e.getMessage());
return null;
}
}
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