package com.inmind.jdk8_time04; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; /** * 目标:掌握JDK 8新增的DateTimeFormatter格式化器的用法。(时间与字符串的互转) */ public class DateTimeFormatterDemo12 { public static void main(String[] args) { //1.创建一个格式化器对象 DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); //2.格式化时间 LocalDateTime now = LocalDateTime.now();//当前时间 Instant instant = Instant.now(); System.out.println(now); String timeStr = dtf.format(now); System.out.println(timeStr); //3.格式化时间,其实还有一种方案。 String timeStr1 = now.format(dtf); System.out.println(timeStr1); //4.解析时间:解析时间一般使用LocalDateTime提供的解析方法来解析。 //注意:在实际开发中,对应的时间,从前端传到后台,一般是字符串,不方便操作时间的,所以要转为时间对象 String birthdayTime = "2006年10月13日"; LocalDate birthdayObj = LocalDate.parse(birthdayTime, dtf); System.out.println(birthdayObj); } }