How to get current Time in Java 8?


From Java8 java.time package was introduced. This provides classes like LocalDate, LocalTime, LocalDateTime, MonthDay etc. Using classes of this package you can get time and date in a simpler way.

Java.time.LocalTime − This class represents a time object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current time from the system clock.

Java.time.LocalDateTime − This class represents a date-time object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date-time from the system clock.

Example

Following example retrieves the current time java.time package of Java8.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class LocalDateJava8 {
   public static void main(String args[]) {
      //Getting the current time value
      LocalTime time = LocalTime.now();
      System.out.println("Current time: "+time);
   }
}

Output

Current time: 18:08:05.923

Example

You can get the time from the LocaldateTime object using the toLocalTime() method. Therefore, another way to get the current time is to retrieve the current LocaldateTime object using the of() method of the same class. From this object get the time using the toLocalTime() method.

import java.time.LocalDateTime;
import java.time.LocalTime;
public class CurentTime {
   public static void main(String args[]) {
      //Getting the current date-time value
      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println("Current date-time: "+dateTime);
      //Getting the time from LocalDateTime object
      LocalTime currentTime = dateTime.toLocalTime();
      System.out.println("Current time"+currentTime);
   }
}

Output

Current date-time: 2019-07-24T19:11:57.467
Current time19:11:57.467

Updated on: 07-Aug-2019

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements