1. Using toString() method
2. Using DateTimeFormatter with custom patterns
Read Also: Convert LocalDate to Date in Java
Let's dive deep into the topic
Format LocalDate to String in Java with Examples
1. Using toString() method
We can easily convert LocalDate to String using the toString() method. LocalDate's class toString() method formats the date in the default format, which is yyyy-MM-dd as shown below in the example.
import java.time.LocalDate; public class LocalDateToString { public static void main(String args[]) { LocalDate date = LocalDate.now(); String str = date.toString(); System.out.println("Converted LocalDate to String: " + str); }
Output:
Converted LocalDate to String: 2023-03-01
2. Using DateTimeFormatter with custom patterns
We can use DateTimeFormatter class's ofPattern() method to provide custom patterns as shown below in the example. To format the LocalDate instance in a date pattern that is not available inbuilt, we can use the format(DateTimeFormatter) method.
import java.time.format.DateTimeFormatter; import java.util.Locale; import java.time.LocalDate; public class LocalDateToString2 { public static void main(String args[]) { LocalDate date = LocalDate.parse("2023-03-01"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.US); String str = date.format(dtf); System.out.println("Converted LocalDate to String: " + str); } }
Output:
Converted LocalDate to String: 01/03/2023
That's all for today. Please mention in the comments if you have any questions related to how to format LocalDate to String in Java with examples.