1

我正在使用 JAXB 和 joda time 2.2。将数据从 Mysql 备份到 XML 并恢复。在我的表中,我有一个格式为“16-Mar-05”的日期属性。我成功地将它存储在 XML 中。但是当我想从 XML 中读取它并将其放回 Mysql 表中时,我无法获得正确的格式。

这是我的 XMLAdapter 类,在 unmarshal 方法中,输入字符串是“16-Mar-05”,但我无法获取格式为“16-Mar-05”的 localDate 变量,尽管我将模式设置为“dd-嗯-yy”。我发布了我尝试过的所有选项,我怎样才能在“dd-MMM-yy”中获得我的 localDate,比如 16-Mar-05 格式?

谢谢!!

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;
    }
}
4

1 回答 1

5

所以我拿了你的代码并运行它,它对我来说很好......

我认为,您遇到的问题是您希望一个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));

生产...

2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05

在您对此感到不安之前,Java 也是这样Date工作的。

于 2013-07-10T01:18:43.263 回答