We can create Instant from Clock. Clock has a timezone.
Clock clock1 = Clock.system(ZoneId.of("Europe/Paris"));
Clock clock2 = Clock.system(ZoneId.of("Asia/Calcutta"));
System.out.println("Clock1 instant: " + clock1.instant());
System.out.println("Clock2 instant: " + clock2.instant());
The output gives the same instant:
Clock1 instant: 2022-01-21T18:36:21.848Z
Clock2 instant: 2022-01-21T18:36:21.848Z
So what is a purpose of having a timezone in Clock?
InstantYou said:
The output gives the same instant:
An Instant is a moment as seen in UTC, that is, with an offset from UTC of zero hours-minutes-seconds. So your code makes no use of your specified time zones.
ZonedDateTimeInstead, try ZonedDateTime. This class does make use of the time zone. For example, calling ZonedDateTime.now() captures the current moment as seen in the JVM’s current default time zone. Calling ZonedDateTime.now( myClock ) captures the current moment tracked by that Clock object as seen through that Clock object’s assigned time zone.
System.out.println("Clock1 ZonedDateTime.now: " + ZonedDateTime.now( clock1 ) );
System.out.println("Clock2 ZonedDateTime.now: " + ZonedDateTime.now( clock2 ) );
See this code run live at IdeOne.com. By the way, there we use the new time zone name Asia/Kolkata rather than Asia/Calcutta.
Notice the different time of day, 16:21 versus 20:51. And notice the different time zone.
Clock1 ZonedDateTime.now: 2022-01-22T16:21:26.490913+01:00[Europe/Paris]
Clock2 ZonedDateTime.now: 2022-01-22T20:51:26.492823+05:30[Asia/Kolkata]
You asked:
So what is a purpose of having a timezone in Clock?
This functionality is useful for testing, where we need to create a known scenario with a specific time zone rather than using the JVM’s actual default time zone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With