Java Reference
In-Depth Information
// Get the current instant of the clock
Instant instant1 = clock.instant();
// Get the current instant using the clock and the Instant class
Instant instant2 = Instant.now(clock);
// Get the local date using the clock
LocalDate ld = LocalDate.now(clock);
// Get the zoned datetime using the clock
ZonedDateTime zdt = ZonedDateTime.now(clock);
The now() method without arguments in all date, time, and datetime classes uses the system default clock for the
default time zone. The following two statements use the same clock:
LocalTime lt1 = LocalTime.now();
LocalTime lt2 = LocalTime.now(Clock.systemDefaultZone());
The systemUTC() method of the Clock class returns a clock for the UTC time zone. You can also obtain a fixed
clock that always returns the same time. A fixed clock is useful in testing when you want your test cases to use
the same current time and not depend on the current time of the system clock. You can use the fixed(Instant
fixedInstant, ZoneId zone) static method of the Clock class to get a clock with a fixed instant in a specified time
zone. The Clock class also lets you obtain a clock that gives time at a fixed offset from another clock.
A clock is always aware of its time zone. You can obtain the system default time zone using the Clock class as
follows:
ZoneId defaultZone = Clock.systemDefaultZone().getZone();
the default implementation of the Clock class ignores the leap seconds. You can also extend the Clock class to
implement your own clock.
Tip
Periods
A period is an amount of time defined in terms of calendar fields years , months , and days . A duration is also an
amount of time measured in terms of seconds and nanoseconds. Negative periods are supported.
What is the difference between a period and a duration? A duration represents an exact number of nanoseconds,
whereas a period represents an inexact amount of time. A period is for humans what a duration is for machines.
Some examples of periods are 1 day, 2 months, 5 days, 3 months and 2 days, etc. When someone mentions a
2 month period, you do not know the exact amount of nanoseconds in that 2 months. A 2 month period may mean
different number of days (and hence different nanoseconds) depending on when that period starts. For example, a
2 month period from midnight January 1 may represent 59 or 60 days depending on whether the year is a leap year or
not. Similarly, a period of 1 day may represent 23, 24, or 25 hours depending on the day whether that day observes the
start/end of the Daylight Saving Time or not.
 
 
Search WWH ::




Custom Search