Get current date and time in java 8

Let’s learn to get current date and time in java 8.

Get current date and time in java 8

In java.time package we have classes LocalDate, LocalTime, LocalDateTime and many more classes to get current date and time.

LocalDate represent a date without a time-zone in the ISO-8601 calendar system.

The ISO-8601 calendar system is the modern civil calendar system used today in most of the world.

now() method of LocalDate class returns the current date using the system clock and default time-zone, not null.

import java.time.LocalTime;
import java.time.ZoneId;
public class CurrentDateTimeJava8 
{
   public static void main(String[] args) 
   {
      LocalTime lt1 = LocalTime.now();
      System.out.println(lt1);
      LocalTime lt2 = LocalTime.now(ZoneId.of("GMT+02:30"));
      System.out.println(lt2);
   }
}



LocalTime class represent a time without a time-zone in the ISO-8601 calendar system.

now() method of LocalTime class returns the current time using the system clock and default time-zone, not null.

LocalDateTime class represent a date-time without a time-zone in the ISO-8601 calendar system.

now() method of LocalDateTime class returns the current date-time using the system clock and default time-zone, not null.

Let’s see an example on above discussed classes.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class CurrentDateTimeJava8 
{
   public static void main(String[] args) 
   {
      LocalDate ld = LocalDate.now();
      System.out.println("Current date: " + ld);
      // get current time value
      LocalTime lt = LocalTime.now();
      System.out.println("Current time: " + lt);
      // get current date-time value
      LocalDateTime ldt = LocalDateTime.now();
      System.out.println("Current date-time: " + ldt);
   }
}


Output:

Current date: 2021-01-13
Current time: 17:23:53.285758100
Current date-time: 2021-01-13T17:23:53.285758100


Also read – nested classes in java