gpt4 book ai didi

java - 字符串到 joda LocalDate,格式为 "dd-MMM-yy"

转载 作者:行者123 更新时间:2023-11-29 04:23:14 25 4
gpt4 key购买 nike

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

这是我的 XMLAdapter 类,这里在 unmarshal 方法中输入字符串是“16-Mar-05”,但我无法以“16-Mar-05”的格式获取 localDate 变量,尽管我将模式设置为“dd-MMM-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;
}
}

最佳答案

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

我认为,您遇到的问题是您期望 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 的工作方式。

关于java - 字符串到 joda LocalDate,格式为 "dd-MMM-yy",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com