Java8为什么需要引入新的日期和时间库Date日期输出可读性较差Date date = new Date();
System.out.println(date);
打印输出的结果:Sat Nov 14 11:03:41 CST 2020
Date日期的解析、格式化通过JDK自带的api实现较为麻烦,通常会使用第三方的日期时间库,比如:joda-time, commons-lang
Java8中提供了哪些日期和时间类
在java.time包中提供了很多新的类,通常主要使用到的是LocalDate, LocalTime, LocalDateTime, ZoneId, ZoneDateTime; 关系图如下:
LocaDate这个类本身不包含时间和时区信息,只包含了日期信息;提供了很多方法来获取常用的值:星期几,几月 ...
常用的静态构造LocaDate方法LocalDate.of(2020, 11, 14); //指定年月日
LocalDate.of(2020, Month.NOVEMBER, 14); //指定年月日 使用Month枚举类
LocalDate.ofYearDay(2020, 10); //2020年第10天 => 2020-01-10
LocalDate.now(); //当前时间
System.out.println(LocalDate.now()); // 比较好的可读性输出 => 2020-11-14
LocaDate常用实例方法LocalDate now = LocalDate.of(2020, 11, 14);
System.out.println(now.getMonth()); //月份的枚举 => NOVEMBER
System.out.println(now.getMonthValue()); //月份的数字 => 11
System.out.println(now.getDayOfMonth()); //几号 => 14
System.out.println(now.getDayOfYear()); // 一年中的第几天 => 319
System.out.println(now.getDayOfWeek()); // 周几枚举 => SATURDAY
System.out.println(now.lengthOfMonth()); //本月多少天 => 30<