我正在阅读文本并将日期存储为 LocalDate 变量。
我有什么办法可以保留 DateTimeFormatter 的格式,这样当我调用 LocalDate 变量时它仍将采用这种格式。
编辑:我希望 parsedDate 以 25/09/2016 的正确格式存储,而不是作为字符串打印
我的代码:
public static void main(String[] args)
{
LocalDate date = LocalDate.now();
DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu");
String text = date.format(formatters);
LocalDate parsedDate = LocalDate.parse(text, formatters);
System.out.println("date: " + date); // date: 2016-09-25
System.out.println("Text format " + text); // Text format 25/09/2016
System.out.println("parsedDate: " + parsedDate); // parsedDate: 2016-09-25
// I want the LocalDate parsedDate to be stored as 25/09/2016
}
原文由 MOZAKATAK 发布,翻译遵循 CC BY-SA 4.0 许可协议
编辑:考虑到您的编辑,只需将 parsedDate 设置为等于您的格式化文本字符串,如下所示:
LocalDate 对象只能以 ISO8601 格式 (yyyy-MM-dd) 打印。为了以其他格式打印对象,您需要对其进行格式化并将 LocalDate 保存为字符串,就像您在自己的示例中演示的那样