JDK1.8版本后增加的日期类
LocalDateTime 类(年月日时分秒)
注意:LocalDateTime 表示一个年月日时分秒的信息,所以在完成格式化和解析时,模板也要是年月日时分秒的模板。否则,抛出异常!
import java.time.LocalDateTime; public class Test { public static void main(String[] args) { //1、获取当前时间 LocalDateTime ldt = LocalDateTime.now(); System.out.println(ldt); //2022-04-08T17:42:48.104859 System.out.println(ldt.getYear()); //2022 //2、自定义时间 LocalDateTime localDateTime = LocalDateTime.of(1990, 6, 7, 11, 15, 43); System.out.println(localDateTime); //1990-06-07T11:15:43 //3、获取单个日期字段 System.out.println(localDateTime.getYear()); //1990 int month = localDateTime.getMonthValue(); System.out.println(month); //6 int day = localDateTime.getDayOfMonth(); System.out.println(day); //7 } }
LocalDateTime 提供的格式化和解析
//获取当前时间 LocalDateTime ldtnow = LocalDateTime.now();
//提供一个模板对象DateTimeFormatter DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//由LocalDateTime提供对应的格式化方法和解析方法 //1.格式化: LocalDateTime -> String String format1 = ldtnow.format(dtf); System.out.println(format1); // 2022-04-08 17:56:23 //2.解析: String -> LocalDatetime LocalDateTime parse = LocalDateTime.parse(format1, dtf); System.out.println(parse); // 2022-04-08T17:56:23
-----------------------------------------------------------------------
LocalDate 类(年月日)
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Test { public static void main(String[] args) { //获取当前日期 LocalDate localDate = LocalDate.now(); System.out.println(localDate); // 2022-04-08
//自定义格式 DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); String format = localDate.format(dtf); System.out.println(format); // 2022年04月08日 } }
------------------------------------------------------------------------
LocalTime 类(时分秒)
import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class Test { public static void main(String[] args) { //获取当前时间 LocalTime localTime = LocalTime.now(); System.out.println(localTime); // 18:10:22.551556900
//自定义格式 DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH时mm分ss秒"); String format1 = localTime.format(dtf); System.out.println(format1); // 18时10分22秒
//解析 LocalTime parse = LocalTime.parse("19时32分15秒", dtf); System.out.println(parse); // 19:32:15 } }