created: 2022-07-24T14:28:17+08:00
updated: 2022-07-24T14:47:35+08:00
tags:
- DateTimeAPI
- DateTimeAPI/Clock
Clock
大多数基于时间的对象提供无参数 now()
方法,该方法使用系统时钟和默认时区提供当前日期和时间。这些基于时间的对象还提供了一个单参数 now(Clock)
方法,允许您传入另一个时钟。
当前日期和时间取决于时区,对于全球化应用程序,时钟是必要的,以确保使用正确的时区创建日期/时间。因此,尽管 Clock
类的使用是可选的,但此功能允许您针对其他时区测试您的代码,或者通过使用时间不会改变的固定时钟来测试您的代码。
Clock
类是抽象的,因此您不能创建它的实例。以下工厂方法可用于测试。
Clock.offset(Clock, Duration)
returns a clock that is offset by the specifiedDuration
.Clock.systemUTC()
returns a clock representing the Greenwich/UTC time zone.Clock.fixed(Instant, ZoneId)
always returns the same Instant. For this clock, time stands still.
[[非ISO日期转换]]