首页 > 解决方案 > Why does the java.time.Clock has zone information?

问题描述

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?

标签: javatimezonejava-timejsr310

解决方案


备用时钟行为

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

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

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


推荐阅读