Convert LocalDateTime to String in Java

  • Last updated Apr 25, 2024

To convert LocalDateTime to a String in Java, you can use the DateTimeFormatter class, which provides a way to format and parse datetime objects. Here's an example code snippet:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Example {

   public static void main(String[] args) {
      // Creating LocalDateTime object
      LocalDateTime currrentLocalDateTime = LocalDateTime.now();

      // Creating DateTimeFormatter object to format datetime
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");

      // Converting from LocalDateTime to String
      String strFormattedLocalDateTime = currrentLocalDateTime.format(formatter);

      // Printing String formatted LocalDateTime
      System.out.println("String formatted LocalDateTime = " + strFormattedLocalDateTime);

   }

}

The output of the above code is as follows:

String formatted LocalDateTime = 2023-04-03 11:06:20 AM

In the above code, we have created a LocalDateTime object using the now() method. We then created a DateTimeFormatter object with the desired datetime format using the ofPattern() method. Finally, we called the format() method on the LocalDateTime object, passing in the DateTimeFormatter object, to get the formatted datetime as a String.

Note that the pattern string used in the DateTimeFormatter constructor can be customized according to your desired datetime format.