JDK1.0中使用java.util.Date类(第一批日期时间API)
JDK1.1引入Calendar类(第二批日期时间API)
缺陷:
可变性:像日期和时间这样的类应该是不可变的
偏移性:Date中的年份是从1900开始的,而月份都从0开始
格式化:格式化只对Date有用,Calendar则不行
因此JDK1.8新增日期时间API:第三批日期时间API:LocalDate&LocalTime&LocalDateTime
package com.pyk.teat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; public class Test04 { public static void main(String[] args) { //1、完成实例化 //方法1:now()--获取当前日期,时间,日期+时间 LocalDate localDate=LocalDate.now(); LocalTime localTime=LocalTime.now(); LocalDateTime localDateTime=LocalDateTime.now(); //方法2:of() localDate =LocalDate.of(2022,5,1); localTime=LocalTime.of(12,23,23); localDateTime=LocalDateTime.of(2022,5,1,12,23,23); //LocalDate和LocalTime不如LocalDateTime多,下面讲解只用LocalDateTime System.out.println(localDateTime.getYear());//2022 System.out.println(localDateTime.getMonth());//MAY System.out.println(localDateTime.getMonthValue());//5 System.out.println(localDateTime.getDayOfMonth());//1 System.out.println(localDateTime.getDayOfWeek());//SUNDAY System.out.println(localDateTime.getHour());//12 System.out.println(localDateTime.getMinute());//23 System.out.println(localDateTime.getSecond());//23 //with:设置 LocalDateTime localDateTime2=localDateTime.withMonth(8); System.out.println(localDateTime); System.out.println(localDateTime2); //以上对比就得知性,只能更改一个新的对象而不能修改原先的对象(不可变性) } }