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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
nantitv
  • 3,539
  • 4
  • 38
  • 61

1 Answers1

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.

Alain O'Dea
  • 21,033
  • 1
  • 58
  • 84
  • Could you please tell me then what is the need of passing Clock as a parameter? – nantitv Jun 27 '15 at 17:51
  • 2
    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. https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html – Alain O'Dea Jun 27 '15 at 17:55
  • @nantitv I've rewritten my answer. It was a bit vague before. Does it answer your question effectively now? – Alain O'Dea Jun 28 '15 at 02:05
  • Please give me some time to digest the concept – nantitv Jun 28 '15 at 07:36