Converting a String into a LocalDate – Java 8
This tutorial shows how to convert a java.lang.String
into a java.time.LocalDate
. We can convert a String into a Date using the parse()
method of the LocalDate
and DateTimeFormatter
classes.
// from java.lang.String into java.time.LocalDate
String dateString = "06-Dec-1989";
LocalDate parsed = DateTimeFormatter.ofPattern("dd-MMM-yyyy").parse(dateString);
// from java.time.LocalDate into java.lang.String
LocalDate localDate = LocalDate.now();
String formatted = DateTimeFormatter.ofPattern("dd-MMM-yyyy").format(localDate)
Convert String = 2016-10-27 to LocalDate
String dateString = "2016-10-27";
LocalDate localDate = LocalDate.parse(dateString);
System.out.println(localDate);
Output:
2016-10-27
Convert String = 27/10/2016 to LocalDate
String dateString = "27/10/2016";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localDate = LocalDate.parse(dateString, formatter);
System.out.println(localDate); // print ISO_LOCAL_DATE by default
System.out.println(formatter.format(localDate));
Output:
2016-10-27
27/10/2016
Convert String = 27 Oct, 2016 to LocalDate
String dateString = "27 Oct, 2016";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMM, yyyy");
LocalDate localDate = LocalDate.parse(dateString, formatter);
System.out.println(localDate); // print ISO_LOCAL_DATE by default
System.out.println(formatter.format(localDate));
Output:
2016-10-27
27 Oct, 2016
Convert String = Thu, Oct 27 2016 to LocalDate
String dateString = "Thu, Oct 27 2016";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, MMM dd yyyy");
LocalDate localDate = LocalDate.parse(dateString, formatter);
System.out.println(localDate); // print ISO_LOCAL_DATE by default
System.out.println(formatter.format(localDate));
Output:
2016-10-27
Thu, Oct 27 2016
Convert String = Thursday, Oct 27, 2016 12:45:13 PM to LocalDateTime
String dateString = "Thursday, Oct 27, 2016 12:45:13 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy HH:mm:ss a");
LocalDateTime localDate = LocalDateTime.parse(dateString, formatter);
System.out.println(localDate); // print ISO_LOCAL_DATE by default
System.out.println(formatter.format(localDate));
Output:
2016-10-27T12:45:13
Thursday, Oct 27, 2016 12:45:13 PM