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