How to use Clock in Java 8?

Java 8Object Oriented ProgrammingProgramming

The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.

The Clock class of the java.time package is used to access the current instant using a time zone. Using this class you can get the current time zone, instant of the clock, current milli seconds etc.

Example

Following Java example demonstrates the usage of Clock class in Java.

import java.time.Clock;
import java.time.ZoneId;
public class CurentTime {
   public static void main(String args[]) {
      //Getting the clock
      Clock clock = Clock.systemUTC();
      System.out.println("Current date: "+clock);
      ZoneId id = clock.getZone();
      System.out.println("zoneId: "+clock.getZone());
      System.out.println("current instant: "+clock.instant());
      //Adding one week to the current date
      Clock defaultClock = Clock.systemDefaultZone();
      System.out.println("Default clock: "+clock);
   }
}

Output

Current date: SystemClock[Z]
zoneId: Z
current instant: 2019-07-25T05:54:06.345Z
Default clock: SystemClock[Z]
raja
Published on 07-Aug-2019 14:48:30
Advertisements