Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLGregorianCalendar to DateTime Java

When I get the DateTime from XML it is XMLGregorianCalendar:

2010-12-02T10:00:00

Than I make a String that looks like this:

2010-12-02 10:00:00

But when I try to parse it into a workable DateTime (joda.datetime) via:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt = formatter.parseDateTime("2010-12-02 10:00:00");

It returns this:

2010-12-02T10:00:00.000+01:00

Where I want it to look like the String but than as DateTime so I can use it....

like image 340
Luc Avatar asked Jun 03 '26 10:06

Luc


2 Answers

The correct way to do this is using the javax.xml.bind.DatatypeConverter class which provides a way to create java.util.Date or java.util.Calendar from the String. You can then easily convert that to Joda time if you want to.

DatatypeConverter docs: http://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/DatatypeConverter.html

like image 132
James Avatar answered Jun 06 '26 00:06

James


I assume the date string you're getting back is basically dt.toString()

You need to format the date using the formatter you have created, otherwise the format bares no relevance. Try this:

System.out.println(formatter.print(dt));

When you set the date using the formatter it purely uses the format you've defined to parse the string... this does not have any effect on the DateTime object so you still need to use your formatter when converting it back to a string

like image 24
Edd Avatar answered Jun 06 '26 00:06

Edd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!