Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Calendar to XMLGregorianCalendar with specific formatting

Tags:

java

I am having some issues in converting a calendar object to an XMLGregorian calendar in the format of YYYY-MM-DD HH:mm:ss.

My current code is:

Calendar createDate = tRow.getBasic().getDateCreated(0).getSearchValue();
Date cDate = createDate.getTime();
GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

which returns a date of 2013-01-03T11:50:00.000-05:00.

I would like it to read 2013-01-03 11:50:00.

I have checked a bunch of posts, which use DateFormat to parse a string representation of the date, however my dates are provided to me as a Calendar object, not a string.

I'd appreciate a nudge in the right direction to help me figure this one out.

like image 227
Robert H Avatar asked Jan 03 '13 20:01

Robert H


1 Answers

An XMLGregorianCalendar has a specific W3C string representation that you cannot change.

However, you can format a Date with SimpleDateFormat.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = dateFormat.format(cDate);

You can get a Date object from a XMLGregorianCalendar object as follows:

xmlCalendar.getGregorianCalendar().getDate()
like image 142
ᴇʟᴇvᴀтᴇ Avatar answered Sep 30 '22 22:09

ᴇʟᴇvᴀтᴇ