Read Also: [Solved] Unable to obtain LocalDateTime from TemporalAccessor
Convert String to LocalDateTime in Java
1. Using parse() method
We can easily convert String to LocalDateTime in Java using LocalDateTime's static parse() method as shown below in the example.
import java.time.LocalDateTime;
public class ConvertStringToLocalDateTime {
public static void main(String args[]) {
// Given String
String dateString = "2018-07-18T08:20:25";
// Convert String to LocalDateTime Object using parse() method
LocalDateTime localdatetime = LocalDateTime.parse(dateString);
// Display LocalDateTime object
System.out.println("Converted String to LocalDateTime: " + localdatetime);
}
}
Output:
Converted String to LocalDateTime: 2018-07-18T08:20:25
Note: The string passed in the parse() method must represent a valid date-time otherwise DateTimeParseException will be thrown.
2. Convert String to LocalDateTime with custom format
We can easily convert String to LocalDateTime with a custom format using the overloaded static parse() method. The overloaded static parse() method takes a String and a DateTimeFormatter as a parameter shown below in the example.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ConvertStringToLocalDateTime2 {
public static void main(String args[]) {
// Given String
String dateString = "2016/09/18 18:11:25";
// Specify date format using DateTimeFormatter
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
// Convert String to LocalDateTime Object using overloaded static parse() method
LocalDateTime localdatetime = LocalDateTime.parse(dateString, dateTimeFormatter);
// Printing LocalDateTime object
System.out.println("Converted String to LocalDateTime: " + localdatetime);
}
}
Output:
Converted String to LocalDateTime: 2016-09-18T18:11:25
That's all for today. Please mention in the comments if you have any questions related to how to convert String to LocalDateTime in Java with examples.