Convert LocalDateTime to String in Java
In Java, you can use the DateTimeFormatter class to convert a LocalDateTime object into a string. Here is an example code:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("Formatted LocalDateTime: " + formattedDateTime);
}
}
In the code above, we begin by creating a LocalDateTime object that represents the current date and time. Then, we use the DateTimeFormatter class to create a formatting template. Finally, we call the format method of the LocalDateTime object to convert it into a string and print it out.