Parsing Strings to Temporal Objects
What you'll learn: How to convert formatted string representations back into temporal objects using parse methods and DateTimeFormatter.
The Reverse Journey
You've learned how to turn temporal objects into formatted strings. Now it's time to go the other direction: taking a string like "2024-01-15" or "03:45 PM" and converting it back into a LocalDate, LocalTime, or other temporal object.
Think of parsing like reading a map. If formatting is drawing directions on paper, parsing is looking at those directions and figuring out where you need to go. The DateTimeFormatter acts as your translation guide, telling Java how to interpret the string's pattern.
How Parsing Works
Each temporal class provides a parse method that accepts a string and a DateTimeFormatter:
String dateText = "15-01-2024";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.parse(dateText, formatter);
// date is now LocalDate of January 15, 2024
For standard ISO formats, you can use the built-in formatters or even parse without specifying a formatter:
LocalDate isoDate = LocalDate.parse("2024-01-15"); // ISO_LOCAL_DATE format
LocalTime time = LocalTime.parse("14:30:00"); // ISO_LOCAL_TIME format
Matching Patterns Precisely
The pattern in your formatter must match the string format exactly. If your string is "Jan 15, 2024", your pattern must be "MMM dd, yyyy". Mismatches throw a DateTimeParseException.
String customFormat = "Jan 15, 2024";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");
LocalDate parsed = LocalDate.parse(customFormat, formatter);
Key Takeaway: Use the parse method with DateTimeFormatter to convert string representations back into temporal objects—just ensure your pattern matches the string format exactly, or you'll get a parsing exception.