Java 8 provides the LocalDate
class and the DateTimeFormatter
class to convert a string representation of a date into a LocalDate
class object.
The
parse
method of theLocalDate
class is used to perform this conversion.
The syntax for the parse
method of the LocalDate
class in Java 8 is:
The code snippet below illustrates how the LocalDate
class and the DateTimeFormatter
class perform the string to date conversion in Java 8:
import java.time.format.DateTimeFormatter;import java.time.LocalDate;class StringToDate {public static void main( String args[] ) {// Example 1DateTimeFormatter formatter_1 = DateTimeFormatter.ofPattern("d/MM/yyyy");String str_date_1 = "24/09/2019";LocalDate local_date_1 = LocalDate.parse(str_date_1, formatter_1);System.out.println(local_date_1);// Example 2DateTimeFormatter formatter_2 = DateTimeFormatter.ofPattern("MMM d yyyy");String str_date_2 = "Sep 24 2019";LocalDate local_date_2 = LocalDate.parse(str_date_2, formatter_2);System.out.println(local_date_2);// Example 3DateTimeFormatter formatter_3 = DateTimeFormatter.ofPattern("d-MMM-yyyy");String str_date_3 = "24-Sep-2019";LocalDate local_date_3 = LocalDate.parse(str_date_3, formatter_3);System.out.println(local_date_3);}}
Free Resources