How to Format LocalDate in Java

Learn to format a Java LocalDate instance to String using inbuilt patterns as well as custom patterns. The default format pattern is ‘yyyy-MM-dd’.

LocalDate today = LocalDate.now();

//1 - Default Format is yyyy-MM-dd
String formattedDate = today.toString(); //2022-02-17

//2 - Inbuilt patterns FULL, LONG, MEDIUM, SHORT
DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
String formattedDate = today.format(pattern);   //17 February 2022

//3 - Custom Pattern
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = today.format(pattern);  //17-02-2022

1. Format LocalDate with Inbuilt Patterns

1.1. Default Pattern [yyyy-MM-dd]

If we use the LocalDate.toString() method, then it formats the date in the default format, which is yyyy-MM-dd.

LocalDate today = LocalDate.now();

System.out.println(today.toString());  //2019-04-03

1.2. Using FormatStyle

The FormatStyle is an immutable and thread-safe enumeration of the style of ‘localized’ date formatters. Based on the Locale, each constant may output a different string.

It has 4 constants for formatting a date:

  • FULL – Thursday, 17 February, 2022
  • LONG – 17 February 2022
  • MEDIUM – 17/02/22
  • SHORT – 4/3/19
LocalDate today = LocalDate.now();

String formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG));   //17 February 2022

formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));  //17-Feb-2022

formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT));  //17/02/22

formattedDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL));  //Thursday, 17 February, 2022

2. Format LocalDate with Custom Patterns

If we have to format the LocalDate instance in a date pattern that is not available inbuilt, we can define our own pattern using LocalDate.format(DateTimeFormatter) method. It accepts a DateTimeFormatter instance that has a list of predefined formats as well as can create a custom format such as ‘dd/MM/yyyy’.

LocalDate today = LocalDate.now();

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = today.format(dateTimeFormatter);  //17-02-2022

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
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

Dark Mode

Dark Mode