Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 219
nantitv Avatar asked Jun 27 '15 17:06

nantitv


People also ask

Should I use LocalDateTime or instant?

Instant and LocalDateTime are two entirely different animals: One represents a moment, the other does not. Instant represents a moment, a specific point in the timeline. LocalDateTime represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment.

What is the difference between LocalDateTime and ZonedDateTime?

A LocalDateTime instance represents a point in the local timeline. It cannot represent an instant on the universal timeline without additional information such as an offset or time zone. A ZonedDateTime instance represents an instant in the universal timeline. It is the combination of date, time and zone information.

Is Instant NOW () UTC?

now() now() method of a Instant class used to obtain the current instant from the system UTC clock. This method will return instant based on system UTC clock.

What is an instant in Java 8 date and time API?

The Java Date Time API was added from Java version 8. instant() method of Clock class returns a current instant of Clock object as Instant Class Object. Instant generates a timestamp to represent machine time. So this method generates a timestamp for clock object.


1 Answers

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.

like image 105
Alain O'Dea Avatar answered Nov 02 '22 21:11

Alain O'Dea