使用 默认模式[yyyy-MM-dd]

如果我们使用 LocalDate.toString()方法,那么它会以默认格式设置日期格式,即 yyyy-MM-dd

  • DateTimeFormatter.ISO_LOCAL_DATE 中引用的默认模式。
  • DateTimeFormatter.ISO_DATE 也会产生相同的结果。
LocalDate today = LocalDate.now();

System.out.println(today.toString());

输出:

2019-04-03
on  it road.com

使用自定义模式

要以其他模式格式化本地日期,我们必须使用 LocalDate.format(DateTimeFormatter) 方法。

Long, medium, short 和 full 格式

DateTimeFormatter.ofLocalizedDate(FormatStyle)支持一些我们可以直接使用的最常用的日期模式。

LocalDate today = LocalDate.now();

String formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG));
System.out.println("LONG format: " + formattedDate);
formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));
System.out.println("MEDIUM format: " + formattedDate);
formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT));
System.out.println("SHORT format: " + formattedDate);
formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL));
System.out.println("FULL format: " + formattedDate);

输出:

LONG format: 	April 3, 2019
MEDIUM format: 	Apr 3, 2019
SHORT format: 	4/3/19
FULL format: 	Wednesday, April 3, 2019

用户定义的模式

如果我们有一个内置不可用的日期模式,我们可以定义自己的模式并使用它。

LocalDate today = LocalDate.now();
String formattedDate = today.format(DateTimeFormatter.ofPattern("dd-MMM-yy"));
System.out.println(formattedDate);

输出:

03-Apr-19
在Java8中如何将 LocalDate 格式化为 String
日期:2020-09-17 00:09:19 来源:oir作者:oir