JDK 8在java.time.format包下还提供了一个DateTimeFormatter类,
该类也是一个格式化类,其功能相当于DataFormat和SimpleDateFormat的合体,
它不仅可以将日期、时间对象格式化成字符串,
还能将特定格式的字符串解析成日期、时间对象。
要使用DateTimeFormatter进行格式化或者解析,就必须先获得DateTimeFormatter对象。
DateTimeFomatter类——获取实例对象方:
1、使用静态常量创建DateTimeFormatter格式器。
在DateTimeFormatter类中包含大量的静态常量,如BASIC_ISO_DATE、ISO_LOCAL_DATE、ISO_LOCAL_TIME等,
通过这些静态常量都可以获取DateTimeFormatter实例。
2、使用不同风格的枚举值来创建DateTimeFormatter格式器。
在FormatStyle类中定义了FULL、LONG、MEDIUM和SHORT四个枚举值,它们表示日期和时间的不同风格。
3、根据模式字符串创建DateTimeFormatter格式器。
使用DateTimeFomatter将日期时间格式化为字符串,可以通过以下两种方法
1、调用DateTimeFormatter的format(TemporalAccessor temporal)方法执行格式化。
其中参数temporal是一个TemporalAccessor类型接口,其主要实现类有LocalDate、LocalDateTime。
2、调用LocalDate、LocalDateTime等日期、时间对象的format(DateTimeFormatter formatter)方法执行格式化。
完成时间日期类的格式化
package changYongLei;
import java.time.*;
import java.time.format.*;
public class GeShiHuaLei_DateTimeFormatter {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter dtf1 = DateTimeFormatter.ISO_DATE_TIME;
System.out.println("使用常量创建DateTimeFormatter:"+dtf1.format(date));
DateTimeFormatter dtf2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println("使用MEDIUM类型风格的DateTimeFormatter:"+dtf2.format(date));
DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("根据模式字符串来创建DateTimeFormatter格式器:"+date.format(dtf3));
System.out.println("根据模式字符串来创建DateTimeFormatter格式器:"+dtf3.format(date));
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e4a56ec29edd6d537f407caba940b5e9.png)
解析字符串
可以通过日期时间对象所提供的parse(CharSequence text, DateTimeFormatter formatter)方法来实现。
解析字符串
package changYongLei;
import java.time.LocalDateTime;
import java.time.format.*;
public class GeShiHuaLei_DateTimeFormatter2 {
public static void main(String[] args) {
String str1 = "2020-05-20 12:36:34";
String str2 = "2020年05月20日 12点36分34秒";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
LocalDateTime ldt1 = LocalDateTime.parse(str1, dtf1);
LocalDateTime ldt2 = LocalDateTime.parse(str2, dtf2);
System.out.println(ldt1);
System.out.println(ldt2);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c0dc99d8c34920f70317da306dda52ee.png)