I am using JAXB and joda time 2.2. to backup the data from Mysql to XML and restore it back. in my Table I have a Date attribute in format of "16-Mar-05". I successfully store this in XML. but when I want to read it from XML and put it back in Mysql table, I cant get the right format.
this is my XMLAdapter class, here in unmarshal method the input String is "16-Mar-05", but I cant get the localDate variable in the format of "16-Mar-05", although I am setting pattern to "dd-MMM-yy". I posted all the options I tried, how can I get my localDate in "dd-MMM-yy" like 16-Mar-05format?
Thanks!!
public class DateAdapter extends XmlAdapter<String, LocalDate> {
// the desired format
private String pattern = "dd-MMM-yy";
@Override
public String marshal(LocalDate date) throws Exception {
//return new SimpleDateFormat(pattern).format(date);
return date.toString("dd-MMM-yy");
}
@Override
public LocalDate unmarshal(String date) throws Exception {
if (date == null) {
return null;
} else {
//first way
final DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
final LocalDate localDate2 = dtf.parseLocalDate(date);
//second way
LocalDate localDate3 = LocalDate.parse(date,DateTimeFormat.forPattern("dd-MMM-yy"));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
return localDate4;
}
}
So I took your code and ran it and it works fine for me...
The problem, I think, you're having is that you're expecting a
LocalDate
object to maintain the format that you original parsed the object with, this is not howLocalDate
works.LocalDate
is a representation of date or period in time, it is not a format.LocalDate
has atoString
method which can be used to dump the value of the object, it, this is a internal format used by the object to provide a human readable representation.To format the date, you need to use some kind of formater, that will take the pattern you want and a date value and return a
String
For example, the following code...
Produced...
Before you get upset about this, this is how Java
Date
works as well.