How to get today's date in Java8?


Prior to Java8 to get current date and time we use to rely on various classes like SimpleDateFormat, Calendar etc.

Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LocalDateJava8 {
   public static void main(String args[]) {
      Date date = new Date();
      String timeFormatString = "hh:mm:ss a";
      DateFormat timeFormat = new SimpleDateFormat(timeFormatString);
      String currentTime = timeFormat.format(date);
      System.out.println("Current time: "+currentTime);
      String dateFormatString = "EEE, MMM d, ''yy";
      DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
      String currentDate = dateFormat.format(date);
      System.out.println("Current date: "+currentDate);
   }
}

Output

Current time: 05:48:34 PM
Current date: Wed, Jul 24, '19

Date and time in Java8

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.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.

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 date, time and date time values using 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 date value
      LocalDate date = LocalDate.now();
      System.out.println("Current date: "+date);
      //Getting the current time value
      LocalTime time = LocalTime.now();
      System.out.println("Current time: "+time);
      //Getting the current date-time value
      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println("Current date-time: "+dateTime);
   }
}

Output

Current date: 2019-07-24
Current time: 18:08:05.923
Current date-time: 2019-07-24T18:08:05.923

Updated on: 07-Aug-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements