Date and Time

How to convert string to localdate in java 8

This post shows you how to convert string to localdate with default timezone and customized timezone.

LocalDate.parse contains two overloaded methods

public static LocalDate parse(CharSequence text)

Obtains an instance of LocalDate from a text string such as 2007-12-03.

public static LocalDate parse(CharSequence text, DateTimeFormatter formatter)

Obtains an instance of LocalDate from a text string using a specific formatter.

Example:

import java.time.Clock;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter; 

public class LocalDateTest 
{
 public static void main(String[] args) 
 {
 
  
 LocalDate stringToLocalDate = LocalDate.parse("2010-11-21");
 System.out.println("Converting string to local date: "+stringToLocalDate );
 
 LocalDate stringToLocalDateFormatter=LocalDate.parse("2010-11-21", DateTimeFormatter.ISO_LOCAL_DATE); 
 System.out.println("Converting string to local date using formatter: "+stringToLocalDateFormatter );
 
 }
}

Output:

Converting string to local date: 2010-11-21
Converting string to local date using formatter: 2010-11-21