前言
- 在java8之前,我们处理日期会存在不少问题,比如日期转换繁琐,计算困难,线程安全等等各种问题。为了解决这些痛处,在java8中引入了java.time包,全新的日期处理方法从根本上解决了这些痛处。
常见的API说明
-
LocalDateTime 表示没有时区的日期时间,一般表示:年月日时分秒,不可变并且线程安全。
-
LocalDate 表示没有时区的日期时间,一般表示:年月日,不可变并且线程安全。
-
LocalTime 表示没有时区的日期时间,一般表示:时分秒,不可变并且线程安全。
-
ZoneId 时区的Id
-
ZonedDateTime 具有时区的日期时间,存储所有日期和时间字段,精度为纳秒,时区为区域偏移量,用于处理模糊的本地日期时间。
-
Instant 对时间轴上的单一瞬时点建模,表示时间线上的一个点(瞬时),主要用于Date和我们新的日期api之间相互转换
-
Duration 表示一段时间,可用于计算两个时间(时分秒等)间隔
-
Period 表示一段时间,可用于计算两个日期(年月日等)间隔
我们主要围绕LocalDate、LocalTime、LocalDateTime三个基础对象来进行演示
使用示例
- 获取当前时间,使用 now() 来创建对象
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now();
Instant instant = Instant.now();
Year year = Year.now();
YearMonth yearMonth = YearMonth.now();
MonthDay monthDay = MonthDay.now();
System.out.println("localDateTime:" + localDateTime);
System.out.println("localDate:" + localDate);
System.out.println("localTime:" + localTime);
System.out.println("zonedDateTime:" + zonedDateTime);
System.out.println("instant:" + instant);
System.out.println("year:" + year);
System.out.println("yearMonth:" + yearMonth);
System.out.println("monthDay:" + monthDay);
---控制台输出---
localDateTime:2021-09-21T20:49:56.544
localDate:2021-09-21
localTime:20:49:56.544
zonedDateTime:2021-09-21T20:49:56.544+08:00[Asia/Shanghai]
instant:2021-09-21T12:49:56.545Z
year:2021
yearMonth:2021-09
monthDay:--09-21
- 使用 of() 指定时间日期的创建
LocalDateTime localDateTime = LocalDateTime.of(2021, 9, 21, 6, 30, 10);
LocalDate localDate = LocalDate.of(2021, 9, 21);
LocalTime localTime = LocalTime.of(6, 30, 10);
System.out.println("localDateTime:" + localDateTime);
System.out.println("localDate:" + localDate);
System.out.println("localTime:" + localTime);
//其中LocalDateTime可以传入localDate和localTime来创建
LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
System.out.println("localDateTime2:" + localDateTime2);
---控制台输出