Using DateTimeFormatter
Example:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateParsing {
public static void main(String[] args) {
String dateStr = "2024-11-24";
// Define the date format pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the date string into a LocalDate object
LocalDate date = LocalDate.parse(dateStr, formatter);
System.out.println("Parsed Date: " + date);
}
}
The DateTimeFormatter uses the ofPattern() method to specify the format. The pattern "yyyy-MM-dd" is the same as in the SimpleDateFormat example.
The parse() method converts the string into a LocalDate object.
Date Format Patterns in DateTimeFormatter: