Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a purpose of ZoneId in java.time.Clock?

Tags:

java

clock

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?

like image 222
Kirill Ch Avatar asked Nov 03 '25 07:11

Kirill Ch


1 Answers

Instant

You 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.

ZonedDateTime

Instead, 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]

Used in testing

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.

like image 164
Basil Bourque Avatar answered Nov 05 '25 22:11

Basil Bourque