如何将LocalDate对象格式化为MM / dd / yyyy并保持格式化

我正在阅读文本并将日期存储为LocalDate变量。

有没有办法让我保留DateTimeFormatter的格式,这样当我调用LocalDate变量时,它仍然是这种格式。

编辑:我希望parsedDate以25/09/2016的正确格式存储,而不是以字符串forms打印

我的代码:

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 } 

编辑:考虑到你的编辑,只需将parsedDate设置为等于你的格式化文本字符串,如下所示:

 parsedDate = text; 

LocalDate对象只能以ISO8601格式打印(yyyy-MM-dd)。 为了以其他格式打印对象,您需要对其进行格式化并将LocalDate保存为字符串,就像您在自己的示例中演示的那样

 DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu"); String text = date.format(formatters); 

只需在打印日期时格式化日期:

 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); System.out.println("Text format " + text); System.out.println("parsedDate: " + parsedDate.format(formatters)); } 

简答:不。

答案很长: LocalDate是一个表示年,月和日的对象,它们将包含三个字段。 它没有格式,因为不同的语言环境将具有不同的格式,并且这将使执行想要在LocalDate上执行的操作(例如添加或减去天数或添加时间)变得更加困难。

String表示(由toString() )是有关如何打印日期的国际标准。 如果您需要不同的格式,则应使用您选择的DateTimeFormatter

如果您可以扩展LocalDate并覆盖toString()方法但LocalDate类是不可变的,因此(secure oop)final是可能的。 这意味着如果您希望使用此类,您将能够使用的唯一toString()方法是上面的(从LocalDate源复制):

 @Override public String toString() { int yearValue = year; int monthValue = month; int dayValue = day; int absYear = Math.abs(yearValue); StringBuilder buf = new StringBuilder(10); if (absYear < 1000) { if (yearValue < 0) { buf.append(yearValue - 10000).deleteCharAt(1); } else { buf.append(yearValue + 10000).deleteCharAt(0); } } else { if (yearValue > 9999) { buf.append('+'); } buf.append(yearValue); } return buf.append(monthValue < 10 ? "-0" : "-") .append(monthValue) .append(dayValue < 10 ? "-0" : "-") .append(dayValue) .toString(); } 

如果必须覆盖此行为,则可以选中LocalDate并使用自定义toString方法,但这可能会导致更多问题而不是解决!