The LocalDate class is a part of Java 8 new date and time API that represents a date without time in the ISO-8601 format (yyyy-MM-dd). This class doesn't store or represent a time or timezone. Instead, it is a description of the date, as used for birthdays and anniversaries.

In this quick article, you'll learn how to format an instance of LocalDate to a date string in Java 8 and higher. LocalDate class provides format() method that accepts an instance of DateTimeFormatter to format this date using the specified format:

public String format(DateTimeFormatter formatter)

DateTimeFormatter specifies the pattern that should be used to format the date and it must not be null. format() returns the formatted date string if the specified pattern is valid.

The following example demonstrates how you can get the current LocalDate instance and then use format() method to convert it into a date string:

// current date
LocalDate now = LocalDate.now();

// format date to string
String dateStr = now.format(DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy"));

// print date strings
System.out.println("Current Date (before): " + now);
System.out.println("Formatted Date (after): " + dateStr);

The above code snippet will output the following:

Current Date (before): 2019-12-30
Formatted Date (after): Monday, December 30, 2019

You can also convert a string to LocalDate and then use format() method to change the date string format as shown below:

// old string format
String oldStr = "12/23/2019";

// parse old string to date
LocalDate date = LocalDate.parse(oldStr, DateTimeFormatter.ofPattern("MM/dd/yyyy"));

// format date to string
String newStr = date.format(DateTimeFormatter.ofPattern("MMMM dd, yyyy"));

// print both strings
System.out.println("Date Format (before): " + oldStr);
System.out.println("Date Format (after): " + newStr);

Now the output should look like below:

Date Format (before): 12/23/2019
Date Format (after): December 23, 2019

Check out How to format a date to string in Java tutorial for more Java 8 new date and time API formatting and parsing examples.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: