I'm looking at the Clock class from java so that I can inject it as a dependency for better testability. But I don't understand the difference between the two methods systemUTC
and systemDefaultZone
. The Instant.now()
seems to be internally using systemUTC
clock whereas YearMonth.now()
uses the systemDefaultZone
clock. I already read the javadoc but it wasn't very clear to me.
I have code that use Instant.now()
and YearMonth.now()
and would like to understand the difference between the two clocks with some examples where using each the clocks wrongly can lead to a problem.
In terms of the instant
method of the two clocks returned by Clock.systemUTC
and Clock.systemDefaultZone
, they will do the same thing. Both of their documentation says that the clocks are "based on the best available system clock". So creating Instant
s using the clocks will always give you the same instant.
The difference in behaviour comes when you try to create a date or time. systemUTC
does this:
Conversion from instant to date or time uses the UTC time-zone.
Whereas systemDefaultZone
does this:
converting to date and time using the default time-zone.
So although both will return the same instant if you ask them what the current instant is, they will not necessarily return the same LocalDateTime
, or LocalDate
, or ZonedDateTime
. For example, suppose my system timezone is Asia/Shanghai
, which is at an offset of UTC+8 all year round. And it is now 5 am on 2020-07-29 in Shanghai. If I do LocalDate.now(Clock.systemUTC())
, it will tell me 2020-07-28
, because it's still the 28th in the UTC timezone. If I do LocalDate.now(Clock.systemDefaultZone())
, however, it will tell me 2020-07-29
, because it is 2020-07-29 in Shanghai (which is the system timezone).
Now you should see why the parameterless now
of date/time related classes use systemDefaultZone
. It would be weird if I did LocalTime.now()
in Shanghai and saw a time that's 8 hours earlier!
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