wykopowiedz1
wykopowiedz1

Reputation: 103

How to mock datetime with java.time.clock?

Why the date generated with below code offset the given time to 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
}

Upvotes: 0

Views: 683

Answers (1)

Anonymous
Anonymous

Reputation: 86296

Why the date generated with below code offset the given time to 11:00:00.00?

Your mock date is 1st January, 2020. According to your link, Belgrade was at offset UTC+1h on this date. From 27th October 2019 until 29th March 2020, more precisely. The mocked date and time is also in UTC, denoted by the trailing Z. When querying the time in your local time zone, Europe/Belgrade, 1 hour is added to the UTC time, so 10:00 becomes 11:00.

You are correct, of course, that Belgrade is at offset +02:00 here in May (because of summer time/DST). Only when converting a date and time in January, the offset that was valid back then is used, not the offset for May.

Repeating your link: 2020 Time Zones - Belgrade

Upvotes: 5

Related Questions