Java Clock

The Java Clock class is used to provide date and time instance using time-zone. A Clock class can be used in place of System.currentTimeMillis() and TimeZone.getDefault() function.

How to use

Use of a Clock class is optional and upon to you. The primary purpose of this class is to allow alternate clocks to be plugged in as and when required. Try the following examples to better understand –

Zone example

The following example program shows how you can get the current zone. If you run the example it will give you the system default zone.

import java.time.Clock;

public class ClockExample1 {

    public static void main(String[] args) {

        // Get system default zone
        Clock clock = Clock.systemDefaultZone();
        System.out.println(clock.getZone());

    }
}

Time miles example

The following example program shows how you can get the current time miles.

import java.time.Clock;

public class ClockExample2 {

    public static void main(String[] args) {

        // Get current time miles
        Clock clock = Clock.systemUTC();
        System.out.println(clock.millis());

        // It will also print the same
        System.out.println(System.currentTimeMillis());

    }
}

Date and time example

The following example program shows how you can get the current date and time.

import java.time.Clock;

public class ClockExample3 {

    public static void main(String[] args) {

        // Get current date and time
        Clock clock = Clock.systemUTC();
        System.out.println(clock.instant());

    }
}