如何使用java.time.clock模拟日期时间?

问题描述 投票:0回答:1

为什么用下面的代码生成的日期将给定时间偏移到11:00:00.00?

test("shouldReturnGivenMockedDateTime") {
  val mockedDateTime = "2020-01-01T10:00:00.00Z"
  val clock: Clock = Clock.fixed(Instant.parse(mockedDateTime), TimeZone.getDefault.toZoneId);
  val result = LocalDateTime.ofInstant(clock.instant, TimeZone.getDefault.toZoneId)
  assert(result.toString == "2020-01-01T10:00") // FALSE!!!
  assert(result.toString == "2020-01-01T11:00") // TRUE
}
java scala datetime java-time
1个回答
4
投票

为什么使用以下代码生成的日期将给定时间偏移到11:00:00.00?

您的模拟日期是2020年1月1日。根据您的链接,贝尔格莱德在该日期的UTC + 1h是偏移时间。从2019年10月27日到2020年3月29日,更确切地说。模拟的日期和时间也以UTC表示,以尾随Z表示。当查询您所在的时区(欧洲/贝尔格莱德)的时间时,UTC时间加了1小时,因此10:00变成11:00。

当然,您是正确的,贝尔格莱德5月在这里偏移+02:00(由于夏令时/夏令时)。仅当转换1月的日期和时间时,才使用当时有效的偏移量,而不是5月的偏移量。

重复您的链接:2020 Time Zones - Belgrade

© www.soinside.com 2019 - 2024. All rights reserved.