In the previous post, we covered a String to Date conversion. In this post, you will learn to convert LocalDate and LocalDateTime to String in Java.
LocalDate and LocalDateTime are immutable date-time objects that represent a date and a date and time.
Both of the examples below make use of java.time package. For more information about Java packages, check out our tutorial on Java Packages.
Convert LocalDate to String in Java
Below is the program that parses a LocaDate object to a String using the DateTimeFormatter class.
import java.time.LocalDate; import java.time.format.DateTimeFormatter; class Test { public static void main(String[] args) { LocalDate localDate = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy"); String dateAsString = localDate.format(formatter); System.out.println(dateAsString); } }
Output: 25 August 2021
Parse LocalDateTime to String in Java
In this example, we are converting a LocalDateTime object into a String.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; class Test { public static void main(String[] args) { LocalDateTime localDate = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss"); String dateAsString = localDate.format(formatter); System.out.println(dateAsString); } }
Output: 25-08-2021 12:00:23