1. 表示日期和时间

1. Instant

表示时刻,不直接对应年月日信息,需要通过时区转换;

// 获取当前时刻
Instant now = Instant.now();
now = Instant.ofEpochMilli(System.currentTimeMillis());

// now = 2022-05-04T10:33:02.521Z

// Instant 和 Date 可以通过纪元时相互转换
public static Instant toInstant(Date date) {
    return Instant.ofEpochMilli(date.getTime());
}

public static Date toDate(Instant instant) {
    return new Date(instant.toEpochMilli());
}

2. LocalDateTime

表示与时区无关的日期和时间;

// 获取系统默认时区的当前日期和时间
LocalDateTime ldt = LocalDateTime.now();

// 直接使用年月日等信息构建 LocalDateTime
LocalDateTime ldt2 = LocalDateTime.of(2022, 5, 4, 16, 56, 36);

// 获取年月日时分秒 星期等信息
System.out.println("ldt.getYear() = " + ldt.getYear());
System.out.println("ldt.getMonthValue() = " + ldt.getMonthValue());
System.out.println("ldt.getDayOfMonth() = " + ldt.getDayOfMonth());
System.out.println("ldt.getHour() = " + ldt.getHour());
System.out.println("ldt.getMinute() = " + ldt.getMinute());
System.out.println("ldt.getSecond() = " + ldt.getSecond());
System.out.println("ldt.getDayOfWeek() = " + ldt.getDayOfWeek());

3. ZoneId/ZoneOffset

LocalDateTime 转换为 Instant 时需要一个参数 ZoneOffset。

ZoneOffset 表示相对于格林尼治的时区差,北京是 +08:00。

// 转换为北京时刻
public static Instant toBeijingInstant(LocalDateTime ldt) {
    return ldt.toInstant(ZoneOffset.of("+08:00"));
}

Instant 有方法根据时区返回一个 ZonedDateTime:

public ZonedDateTime atZone(ZoneId zone) {
    return ZonedDateTime.ofInstant(this, zone);
}

默认时区

ZoneId systemDefault = ZoneId.systemDefault();

构建 ZoneId(ZoneOffset 是 ZoneId 的子类,可以根据时区差构造)