该类在java.time.format包下,用于格式化和解析日期,类似于SimpleDateFormat。
一、常用方法
二、格式化方法
1.预定义的标准格式
ISO_LOCAL_DATE_TIME、ISO_LOCAL_DATE、ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime now = LocalDateTime.now();
String str1 = formatter.format(now);
System.out.println("格式化之前:"+now);
System.out.println("格式化之后"+str1);
TemporalAccessor parse = formatter.parse("2021-07-21T18:27:42.46");
System.out.println(parse);
2.本地化相关的格式
(1)ofLocalizedDateTime():
FormatStyle.LONG、FormatStyle.MEDIU、FormatStyle.SHORT
注:适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
DateTimeFormatter formatter3 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter1.format(localDateTime);
String str2 = formatter2.format(localDateTime);
String str3 = formatter3.format(localDateTime);
System.out.println("格式化之前:"+localDateTime);
System.out.println("格式化之后SHORT:"+str1);
System.out.println("格式化之后LONG:"+str2);
System.out.println("格式化之后MEDIUM:"+str3);
TemporalAccessor parse1 = formatter1.parse("21-7-21");
TemporalAccessor parse2 = formatter2.parse("2021年7月21日");
TemporalAccessor parse3 = formatter3.parse("2021-7-21");
System.out.println(parse1);
System.out.println(parse1);
System.out.println(parse3);
(2)ofLocalizedDate()
FormatStyle.FULL、FormatStyle.LONG、FormatStyle.MEDIUM、FormatStyle.SHORT
注:适用于LocalDte
DateTimeFormatter formatter4 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
LocalDate now = LocalDate.now();
String str4 = formatter4.format(now);
System.out.println("格式化之前"+now);
System.out.println("格式化后FULL:"+str4);
三、自定义的格式
ofPattern(“yyyy-MM-dd hh:mm:ss”)
注:这种方式最常用
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
LocalDateTime now = LocalDateTime.now();
String str1 = formatter.format(now);
System.out.println(now);
System.out.println(str1);
TemporalAccessor parse = formatter.parse("2021-07-21 07:17:34");