Java Convert String to LocalDate

Learn to convert string to LocalDate object in Java. java.time.LocalDate instances are immutable and thread-safe, which makes it very useful for robust application design. Also see some useful date pattern strings, which will help you in building your own custom date pattern.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String dateString = "14/07/2018";

LocalDate localDateObj = LocalDate.parse(dateString, dateTimeFormatter);	//String to LocalDate

String dateStr = localDateObj.format(dateTimeFormatter);		//LocalDate to String


Quick example to parse date strings to LocalDate objects and vice-versa, using DateTimeFormatter class.

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class Main 
	public static void main(String[] args) throws ParseException 
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
		String dateString = "14/07/2018";
		//string to date
		LocalDate localDate = LocalDate.parse(dateString, dateTimeFormatter);
		//date to string
		String dateStr = localDate.format(dateTimeFormatter);
		System.out.println(localDate);		// 2018-07-14
		System.out.println(dateStr);		// 14/07/2018

Default pattern used in LocalDate

Default LocalDate.parse(dateString) method, uses the ISO_LOCAL_DATE formatter.

String dateString = "2018-07-14";		//ISO date
//string to date
LocalDate localDate = LocalDate.parse( dateString );		//2018-07-14

//date to string
String dateStr = localDate.format( DateTimeFormatter.ISO_LOCAL_DATE );		//14/07/2018

Useful Date Patterns

Pattern Example
yyyy-MM-dd (ISO) “2018-07-14”
dd-MMM-yyyy “14-Jul-2018”
dd/MM/yyyy “14/07/2018”
E, MMM dd yyyy “Sat, Jul 14 2018”
h:mm a “12:08 PM”
EEEE, MMM dd, yyyy HH:mm:ss a “Saturday, Jul 14, 2018 14:31:06 PM”
yyyy-MM-dd'T'HH:mm:ssZ “2018-07-14T14:31:30+0530”
hh 'o''clock' a, zzzz “12 o’clock PM, Pacific Daylight Time”
K:mm a, z “0:08 PM, PDT”

Checkout DateTimeFormatter to build your own custom patterns using date and time formatting symbols.

Happy Learning !!

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial