use*_*855 1 java mysql jaxb jodatime
我正在使用JAXB和joda时间2.2.将数据从Mysql备份到XML并将其还原.在我的表中,我有一个Date属性,格式为"16-Mar-05".我成功地将其存储在XML中.但是当我想从XML中读取它并将其放回Mysql表中时,我无法获得正确的格式.
这是我的XMLAdapter类,这里的unmarshal方法输入String是"16-Mar-05",但我不能以"16-Mar-05"的格式获取localDate变量,虽然我将模式设置为"dd- MMM-YY".我发布了我尝试过的所有选项,如何在16d-05-05格式的"dd-MMM-yy"中获取我的localDate?
谢谢!!
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我拿了你的代码并运行它,它对我来说很好......
这个问题,我想,你遇到的是,你希望一个LocalDate对象,以保持与您原有的解析对象的格式,这不是多么LocalDate的作品.
LocalDate 是日期或时间段的表示,它不是格式.
LocalDate有一个toString方法可以用来转储对象的值,它,这是一个由对象用来提供人类可读表示的内部格式.
要格式化日期,您需要使用某种格式化程序,它将采用您想要的模式和日期值并返回 String
例如,以下代码......
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String date = "16-Mar-05";
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
LocalDate localDate2 = dtf.parseLocalDate(date);
System.out.println(localDate2 + "/" + dtf.print(localDate2));
//second way
LocalDate localDate3 = LocalDate.parse(date, DateTimeFormat.forPattern("dd-MMM-yy"));
System.out.println(localDate3 + "/" + dtf.print(localDate3));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
System.out.println(localDate4 + "/" + FORMATTER.print(localDate4));
Run Code Online (Sandbox Code Playgroud)
产...
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
Run Code Online (Sandbox Code Playgroud)
在您对此感到不安之前,这也是Java的Date工作方式.