created: 2022-07-15T17:52:44+08:00
updated: 2022-07-17T16:15:14+08:00
tags:
- DateTimeAPI
The Date Time API Overview
Introducing Date Time APIs
Date-Time API 使用 ISO-8601 中定义的日历系统作为默认日历。如果您想使用其他日历系统,例如 Hijrah 或 Thai Buddhist,java.time.chrono 包允许您使用预定义的日历系统之一。
Date Time Design Principles
Clear
API 中的方法定义良好,其行为清晰且符合预期。例如,使用 null 参数值调用 Date-Time 方法通常会触发 NullPointerException。
Fluent
Date-Time API 提供了fluent interface,使代码易于阅读。
LocalDate today = LocalDate.now();
LocalDate payday = today.with(TemporalAdjusters.lastDayOfMonth()).minusDays(2);
Immutable
Date-Time API 中的大多数类创建的对象都是不可变的,这意味着对象创建后就无法修改。要更改不可变对象的值,必须将新对象构造为原始对象的修改副本。这也意味着 Date-Time API 根据定义是线程安全的。这会影响 API,因为用于创建日期或时间对象的大多数方法都以 of、from 或 with 为前缀,而不是构造函数,并且没有 set 方法。例如:
LocalDate dateOfBirth = LocalDate.of(2012, Month.MAY, 14);
LocalDate firstBirthday = dateOfBirth.plusYears(1);
Extensible
Date-Time API 是可扩展的,只要有可能。例如,您可以定义自己的时间调整器和查询,或构建自己的日历系统。
The Date Time Packages
Date-Time API 由主包 java.time 和四个子包组成:
-
java.time
表示日期和时间的 API 的核心。它包括日期、时间、日期和时间组合、时区、瞬间、持续时间和时钟的类。这些类基于 ISO-8601 中定义的日历系统,并且是不可变的和线程安全的。 -
java.time.chrono
用于表示除默认 ISO-8601 之外的日历系统的 API。您还可以定义自己的日历系统。 -
java.time.format
用于格式化和解析日期和时间的类。 -
java.time.temporal
扩展 API,主要用于框架和库编写者,允许日期和时间类之间的互操作、查询和调整。此包中定义了字段(TemporalField 和 ChronoField)和单位(TemporalUnit 和 ChronoUnit)。 -
java.time.zone
支持时区、时区偏移和时区规则的类。如果使用时区,大多数开发人员将只需要使用 ZonedDateTime、ZoneId 或 ZoneOffset。
Method Naming Conventions
Prefix | Method Type | Use |
---|---|---|
of | static factory | Creates an instance where the factory is primarily validating the input parameters, not converting them. |
from | static factory | Converts the input parameters to an instance of the target class, which may involve losing information from the input. |
parse | static factory | Parses the input string to produce an instance of the target class. |
format | instance | Uses the specified formatter to format the values in the temporal object to produce a string. |
get | instance | Returns a part of the state of the target object. |
is | instance | Queries the state of the target object. |
with | instance | Returns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean. |
plus | instance | Returns a copy of the target object with an amount of time added. |
minus | instance | Returns a copy of the target object with an amount of time subtracted. |
to | instance | Converts this object to another type. |
at | instance | Combines this object with another. |
[[标准日历]]