Clock

Description

Clock class represents the real-world clock.

We can access to the current instant, date, and time in a time zone from Clock class.

We can create a clock for the system default time zone as follows.

Clock clock = Clock.systemDefaultZone();

To create a clock for a specified time zone.


ZoneId  z = ZoneId.of("America/Los_Angeles"); 
Clock  clock2 = Clock.system(z);

Example

To get the current instant, date, and time from a clock, use the now(Clock c) method of the datetime related classes.


import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZonedDateTime;
/*from  ww  w. j  av a 2  s .  c  o  m*/
public class Main {
  public static void main(String[] args) {
    Clock clock = Clock.systemDefaultZone();

    Instant instant1 = clock.instant();
    System.out.println(instant1);

    Instant instant2 = Instant.now(clock);
    System.out.println(instant2);

    LocalDate localDate = LocalDate.now(clock);
    System.out.println(localDate);

    ZonedDateTime zoneDateTime = ZonedDateTime.now(clock);
    System.out.println(zoneDateTime);
  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial