Documentation

The Java™ Tutorials
Hide TOC
Date-Time Design Principles日期时间设计原则
Trail: Date Time
Lesson: Date-Time Overview

Date-Time Design Principles日期时间设计原则

The Date-Time API was developed using several design principles.日期时间API是使用几种设计原则开发的。

Clear

The methods in the API are well defined and their behavior is clear and expected. API中的方法定义得很好,它们的行为也很清晰,符合预期。For example, invoking a Date-Time method with a null parameter value typically triggers a NullPointerException.例如,使用null参数值调用日期时间方法通常会触发NullPointerException

Fluent流畅的

The Date-Time API provides a fluent interface, making the code easy to read. 日期时间API提供了一个流畅的界面,使代码易于阅读。Because most methods do not allow parameters with a null value and do not return a null value, method calls can be chained together and the resulting code can be quickly understood. 由于大多数方法不允许参数为null值,也不返回null值,因此可以将方法调用链接在一起,从而可以快速理解生成的代码。For example:例如:

LocalDate today = LocalDate.now();
LocalDate payday = today.with(TemporalAdjusters.lastDayOfMonth()).minusDays(2);

Immutable不变的

Most of the classes in the Date-Time API create objects that are immutable, meaning that, after the object is created, it cannot be modified. Date-Time API中的大多数类创建的对象都是不可变的,这意味着,在创建对象之后,不能对其进行修改。To alter the value of an immutable object, a new object must be constructed as a modified copy of the original. 要更改不可变对象的值,必须将新对象构造为原始对象的修改副本。This also means that the Date-Time API is, by definition, thread-safe. 这也意味着,根据定义,日期时间API是线程安全的。This affects the API in that most of the methods used to create date or time objects are prefixed with of, from, or with, rather than constructors, and there are no set methods. 这会影响API,因为用于创建日期或时间对象的大多数方法的前缀都是offromwith,而不是构造函数,并且没有set方法。For example:例如:

LocalDate dateOfBirth = LocalDate.of(2012, Month.MAY, 14);
LocalDate firstBirthday = dateOfBirth.plusYears(1);

Extensible可扩展

The Date-Time API is extensible wherever possible. 日期-时间API在任何可能的地方都是可扩展的。For example, you can define your own time adjusters and queries, or build your own calendar system.例如,您可以定义自己的时间调整器和查询,或者构建自己的日历系统。


Previous page: Date-Time Overview
Next page: The Date-Time Packages