I have a date field, which when converted to xml using XStream, gives time in milliseconds and zone. I just need to convert or format it as "MMMM dd, yyyy HH:mm:ss"
. How to do that using XStream? I don't want to change the getters and setters. Thanks.
My class:
public class Datas {
private String name;
private Calendar dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Calendar getDob() {
return dob;
}
public void setDob(Calendar dob) {
this.dob = dob;
}
public static void main(String[] args) {
Datas datas = new Datas();
datas.setName("Ahamed");
datas.setDob(Calendar.getInstance());
XStream stream = new XStream();
System.out.println(stream.toXML(datas));
}
}
Output:
<Datas>
<name>Ahamed</name>
<dob>
<time>1329081818801</time>
<timezone>Asia/Calcutta</timezone>
</dob>
</Datas>
I would like to format the dob tag without changing the getters and setters. Thanks.
An easy way is to register an (XStream!) DateConverter with the appropriate formats, e.g.:
import com.thoughtworks.xstream.converters.basic.DateConverter;
XStream xstream = new XStream();
String dateFormat = "yyyyMMdd";
String timeFormat = "HHmmss";
String[] acceptableFormats = {timeFormat};
xstream.registerConverter(new DateConverter(dateFormat, acceptableFormats));
This works for me and I didn't need to create a new converter class.