java 8 time api - Instant.now(clock) vs LocaldateTime.now(clock)
Asked Answered
G

1

12

For following code for java 8

  1. System.out.println(LocalDateTime.now(Clock.systemDefaultZone())); 
  2. System.out.println(Instant.now(Clock.systemDefaultZone()));

Line 1 print current time by adding offset but line 2 print current time without adding offset.

I checked the source code of both and found that LocaDateTime.now(clock) return clock.instant() return time by adding offset but Instant.now(clock) not doing so.

Why it designed like this? Aren't we expecting same result in both case?

Germanize answered 27/6, 2015 at 17:0 Comment(0)
F
11

UPDATE: Instant has nothing to do with UTC in the timezone sense. It is related to UTC as a time standard only.

The major difference is the return type. They have different String representations because the types themselves have very different meanings.

Instant#now(Clock) returns Instant. An Instant is "[a]n instantaneous point on the time-line".

LocalDate#now(Clock) returns LocalDate. A LocalTime is "a description of the local time as seen on a wall clock".

As a result Instant#now(Clock) and LocalDate#now(Clock) mean very different things and naturally have different outcomes. The major thing they have in common is a name. Method names are dust. Refer to the types.

On a fixed Clock, both Instant.now(clock) and LocalDate.now(clock) will return constant values. The point of accepting Clock as a parameter is to be able to control things like the reference time or clock resolution.

Flatten answered 27/6, 2015 at 17:8 Comment(4)
Could you please tell me then what is the need of passing Clock as a parameter?Germanize
Clock is allowed as a parameter to permit use cases like a fixed or offset clock in testing or different resolutions like seconds or minutes as required. docs.oracle.com/javase/8/docs/api/java/time/Clock.htmlSelfgovernment
@Germanize I've rewritten my answer. It was a bit vague before. Does it answer your question effectively now?Selfgovernment
Please give me some time to digest the conceptGermanize

© 2022 - 2024 — McMap. All rights reserved.