How to convert Date to String in Java 8?


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.

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.

The toString() method of the LocalDate class converts the date value of the current Date object in to String and returns it.

Example

Following Java example accepts month, year and, day values from user, creates a date object from it and, converts it to String.

import java.time.LocalDate;
import java.util.Scanner;
public class DateToString {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      System.out.println("Enter the month: ");
      int month = sc.nextInt();
      System.out.println("Enter the day: ");
      int day = sc.nextInt();
      //Getting the given date value
      LocalDate givenDate = LocalDate.of(year, month, day);
      //Converting given date to String
      String date = givenDate.toString();
      System.out.println("Given date :"+date);
   }
}

Output

Enter the year:
2019
Enter the month:
09
Enter the day:
26
Given date :2019-09-26

Updated on: 07-Aug-2019

459 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements