Java java.time.Clock class code examples [Java Date Time API]


Java Clock Class from Date Time API
Java Clock Class from Date Time API

Java introduced the new Date & Time API as java.time package with Java 8 by adding all that was missing while dealing with Date/Time/Time Zones, one of such classes is called the Clock.

⛏️ The Instances of Clock class can be used to get the current instant, date, and time using a time zone.

Example:
Clock newYorkClock = Clock.system(ZoneId.of("America/New_York"));

You may not often use Clock class while dealing with date/time. When you create the objects of LocalDate, LocalDateTime, Instant, or ZonedDateTime, you would notice that the API makes use of the Clock class to get you the date and time.

Example: now method of LocalDate
public static LocalDate now() {
        return now(Clock.systemDefaultZone());
    }
Example: now method of Instant
public static Instant now() {
        return Clock.systemUTC().instant();
    }

The Clock gets the date/time from the system clock in the default time zone.



Some methods of java.time.Clock class

1. public static Clock systemUTC()
Example:
    public static void main(String[] args) {
       Clock clockUtc = Clock.systemUTC();
       Instant instantUtc = clockUtc.instant();
       System.out.println(instantUtc);
    }

2022-05-14T11:21:22.192486Z



2. public static Clock systemDefaultZone()
Example:

This will get the Clock object based on the System Timezone which is America/New_York in this case,

    public static void main(String[] args) {
        Clock clockDefaultTimeZone = Clock.systemDefaultZone();
        System.out.println(clockDefaultTimeZone.getZone());
    }

America/New_York



3. public static Clock system(ZoneId zone)
Example:

This will get the Clock object based on the set Time ZoneID and using the best available system clock, it may use the System.currentTimeMillis() or any other higher resolution clock if one is available,

public static void main(String[] args) {
  Clock systemClockTimeAmericaChicago = Clock.system(ZoneId.of("America/Chicago"));
  System.out.println(systemClockTimeAmericaChicago.getZone());
}

America/Chicago



4. public static Clock tickMillis(ZoneId zone)

Example:

This method was introduced in Java 9, it returns the Clock with the current instant ticking in whole milliseconds using the best available system clock.

Clock systemClockTimeAmericaChicago = Clock.tickMillis(ZoneId.of("America/Chicago"));


5. public static Clock tickSeconds(ZoneId zone)

Example:
Clock systemClockTimeAmericaChicago = Clock.tickSeconds(ZoneId.of("America/Chicago"));


6. public static Clock tickMinutes(ZoneId zone)

Example:
Clock systemClockTimeAmericaChicago = Clock.tickMinutes(ZoneId.of("America/Chicago"));
Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap