Convert String to LocalDateTime and LocalDateTime to String in Java
The following code converts String to LocalDateTime in Java:
String datetimeStr = "2021-05-10 11:50:10";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(datetimeStr, formatter);
System.out.println("String to LocalDateTime = " + localDateTime);
Output:
String to LocalDateTime = 2021-05-10T11:50:10
The following code shows how to convert LocalDateTime to String in Java:
LocalDateTime currrentLocalDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedLocalDateTime = currrentLocalDateTime.format(formatter);
System.out.println("LocalDateTime to String = " + formattedLocalDateTime);
Output:
LocalDateTime to String = 2021-05-29 00:54:44