Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 976
James Avatar asked Nov 28 '18 10:11

James


2 Answers

I suppose it takes a bit of mind reading or guessing to answer your question, but let me try anyway. As far as I can see, the Clock knowing a time zone is very convenient when using any of the now methods taking a Clock argument. None of the following methods could work correctly if the Clock wasn’t able to provide a time zone:

  • LocalDate.now(Clock)
  • LocalDateTime.now(Clock)
  • LocalTime.now(Clock)
  • MonthDay.now(Clock)
  • OffsetDateTime.now(Clock)
  • OffsetTime.now(Clock)
  • Year.now(Clock)
  • YearMonth.now(Clock)
  • ZonedDateTime.now(Clock)
  • HijrahDate.now(Clock)
  • JapaneseDate.now(Clock)
  • MinguoDate.now(Clock)
  • ThaiBuddhistDate.now(Clock)

The list may not be complete. Only Instant.now(Clock) doesn’t need a time zone and ignores the time zone of the Clock.

And yes, the alternative design where Clock had a zonedDateTime method providing the same result as ZonedDateTime.now(Clock) would have made sense too. However: Someone wanting to develop, say, a JewishDate class would never be able to insert a jewishDate method into the Clock class. With the existing design they can design their JewishDate class along the exact same lines as the existing date and time classes, including a JewishDate.now(Clock) method.

like image 82
Ole V.V. Avatar answered Oct 04 '22 01:10

Ole V.V.


Alternate clock behaviors

Quoting the Clock documentation (emphasis mine):

Use of a Clock is optional. All key date-time classes also have a now() factory method that uses the system clock in the default time zone. The primary purpose of this abstraction is to allow alternate clocks to be plugged in as and when required. Applications use an object to obtain the current time rather than a static method. This can simplify testing.

For example, Clock.fixed( Instant fixedInstant, ZoneId zone ) always reports the current moment as a specific moment, a fixed (non-changing) point in time.

like image 32
Martin of Hessle Avatar answered Oct 04 '22 01:10

Martin of Hessle