处理跨时区的日期和时间,并管理由夏时制导致的更改,包括格式化日期和时间值。

核心时区类

Java8之前处理时区信息使用java.util.TimeZone。更新了新的API
位于java.time 包中,并且是不可变的final
image.png

  • ZoneId
    时区的ID,例如Asia/Tokyo
  • ZoneOffset
    时区偏移量。它是ZoneId的子类,例如-06:00
  • ZonedDateTime
    带有时区信息的日期/时间。 2015-08-30T20:05:12.463-05:00[America/Mexico_City]
  • OffsetDateTime
    表示与 UTC/Greenwich 有偏移的日期/时间,例如,2015-08-30T20:05:12.463-05:00。
  • OffsetTime
    表示与 UTC/Greenwich 有偏移的时间。例如,20:05:12.463-05:00

ZoneId和ZoneOffset类

世界被划分为若干个时区,在这些时区内保持相同的标准时间。按照惯例,时区表示为与协调世界协调世界时(UTC)不同的小时数
Java 使用互联网号码分配局时区数据库,它保存着全世界所有已知时区的记录,并且每年更新多次。

  • static 方法得到所有可用的区域 id

ZoneId

是一个抽象类

  • 所有可用的区域 id
Set<String> getAvailableZoneIds()
  • 要获取系统的区域 ID
ZoneId.systemDefault()
  • 创建一个特定的 ZoneId 对象
ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
  • 使用规则
    1.如果区域ID等于Z,则结果为ZoneOffset.UTC。任何其他字母都会抛出异常。
    2.如果区域ID以+或-,则使用ZoneOffset.of(String)将ID解析为ZoneOffset。
    3.如果区域ID等于GMT、UTC或UT,则结果是具有相同ID的区域ID和与ZoneOffset.UTC等效的规则。
    4.如果区域ID以UTC+、UTC-、GMT+、GMT-、UT+或UT-开头,则ID将一分为二,前缀为两个或三个字母,后缀以符号开头。后缀被解析为区域偏移。结果将是具有指定前缀和规范化偏移ID的ZoneId。
    5.所有其他ID都被解析为基于区域的区域ID。如果格式无效(必须与表达式[A-Za-z][A-Za-z0-9~/.-]+]匹配)或未找到,则会引发异常。
    image.png
    如果向这些方法中的任何一个传递无效的格式或超出范围的值,则会引发异常。

ZonedDateTime类

相对于时区的时间点,包括日期、时间、时区。
它存储所有日期和时间字段,精度为纳秒,以及带有区域偏移的时区。

ZoneId 对象,你可以将它与 LocalDate、 LocalDateTime 或 Instant 组合起来,将其转换为 ZonedDateTime

ZoneId australiaZone = ZoneId.of("Australia/Victoria");

LocalDate date = LocalDate.of(2010, 7, 3);
ZonedDateTime zonedDate = date.atStartOfDay(australiaZone);

LocalDateTime dateTime = LocalDateTime.of(2010, 7, 3, 9, 0);
ZonedDateTime zonedDateTime = dateTime.atZone(australiaZone);

Instant instant = Instant.now();
ZonedDateTime zonedInstant = instant.atZone(australiaZone);

或者使用of方法

ZonedDateTime zonedDateTime2 =
    ZonedDateTime.of(LocalDate.now(), LocalTime.now(), australiaZone);
ZonedDateTime zonedDateTime3 =
    ZonedDateTime.of(LocalDateTime.now(), australiaZone);
ZonedDateTime zonedDateTime4 =
    ZonedDateTime.ofInstant(Instant.now(), australiaZone);
// year, month, day, hours, minutes, seconds, nanoseconds, zoneId
ZonedDateTime zonedDateTime5 =
    ZonedDateTime.of(2015,1,30,13,59,59,999, australiaZone);

夏令时

在夏天将时钟提前一个小时,当夏令时开始的时候,当日光时间结束时,时钟被调慢一个小时。这样做是为了更好地利用自然光。

//TODO


这个家伙很懒,啥也没有留下😋