日期时间API概述


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

PrefixMethod TypeUse
ofstatic factoryCreates an instance where the factory is primarily validating the input parameters, not converting them.
fromstatic factoryConverts the input parameters to an instance of the target class, which may involve losing information from the input.
parsestatic factoryParses the input string to produce an instance of the target class.
formatinstanceUses the specified formatter to format the values in the temporal object to produce a string.
getinstanceReturns a part of the state of the target object.
isinstanceQueries the state of the target object.
withinstanceReturns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean.
plusinstanceReturns a copy of the target object with an amount of time added.
minusinstanceReturns a copy of the target object with an amount of time subtracted.
toinstanceConverts this object to another type.
atinstanceCombines this object with another.

[[标准日历]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值