How to convert string to date in Java 8

Let’s learn how to convert string to date in Java 8.

How to convert string to date in Java 8

Let’s see example in converting String to Date using LocalDate class and DateTimeFormatter class in Java 8.

Syntax:

LocalDate ld = LocalDate.parse(date, formatter);

parse() method returns the parsed local date, not null. Let’s see convert string to date in java 8 example.

import java.time.LocalDate;
import java.time.LocalDateTime;
public class Java8StringToDate
{
   public static void main(String[] args)
   {
      DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("d/MM/yyyy");
      String strDate1 = "14/05/2007";
      LocalDate ld1 = LocalDate.parse(strDate1, dtf1); 
      System.out.println(ld1);
      DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM d yyyy");
      String strDate2 = "May-14-2007";
      LocalDate ld2 = LocalDate.parse(strDate2, dtf2); 
      System.out.println(ld2);
   }
}


Output:

2007-05-14
2007-05-14


Also read – Arrays in java