13

Why does java.time.Clock has zone information? From the Clock you only can get an Instant when calling the instant() method - which is a time without zone info.

Is the only purpose to have the zone available in the clock to e.g. create a ZonedDateTime like this? ZonedDateTime.ofInstant(clock().instant(), clock().getZone())

Wouldn't it then make sense to have a method zonedDateTime() in the Clock class?

4

2 回答 2

7

备用时钟行为

引用Clock文档(强调我的):

时钟的使用是可选的。所有关键的日期时间类也有一个 now() 工厂方法,它使用默认时区的系统时钟。这种抽象的主要目的是允许在需要时插入备用时钟。应用程序使用对象而不是静态方法来获取当前时间。这可以简化测试。

例如,Clock.fixed( Instant fixedInstant, ZoneId zone )始终将当前时刻报告为特定时刻,即固定(不变)的时间点。

于 2018-11-28T11:26:25.507 回答
4

我想回答你的问题需要一些读心术或猜测,但无论如何让我试试。据我所知,在使用任何带参数的方法Clock时,知道时区非常方便。如果无法提供时区,则以下方法均无法正常工作:nowClockClock

该列表可能不完整。仅Instant.now(Clock)不需要时区并忽略Clock.

是的,替代设计Clock有一种方法可以提供与有意义zonedDateTime的结果相同的结果。ZonedDateTime.now(Clock)但是:想要开发一个JewishDate类的人永远无法将jewishDate方法插入到Clock该类中。使用现有的设计,他们可以JewishDate按照与现有日期和时间类完全相同的方式设计他们的类,包括一个JewishDate.now(Clock)方法。

于 2018-11-29T07:54:28.473 回答