How to Use DateTimeFormatter in Java: Simple Guide
Use
DateTimeFormatter in Java to format and parse date-time objects by defining a pattern string. Create a formatter with DateTimeFormatter.ofPattern() and apply it to LocalDate, LocalTime, or LocalDateTime objects using format() or parse() methods.Syntax
The basic syntax to create a DateTimeFormatter is using DateTimeFormatter.ofPattern(String pattern). The pattern defines how the date and time will be formatted or parsed.
- Pattern: A string like
"yyyy-MM-dd"that specifies the date/time format. - format(): Method to convert a date/time object to a string.
- parse(): Method to convert a string back to a date/time object.
java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDate = formatter.format(LocalDateTime.now()); LocalDateTime dateTime = LocalDateTime.parse("2024-06-01 15:30:00", formatter);
Example
This example shows how to format the current date and time into a string and then parse a string back into a LocalDateTime object using DateTimeFormatter.
java
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterExample { public static void main(String[] args) { // Create a formatter with a pattern DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // Format current date-time to string LocalDateTime now = LocalDateTime.now(); String formattedDate = now.format(formatter); System.out.println("Formatted date-time: " + formattedDate); // Parse string back to LocalDateTime String dateString = "2024-06-01 15:30:00"; LocalDateTime parsedDate = LocalDateTime.parse(dateString, formatter); System.out.println("Parsed LocalDateTime: " + parsedDate); } }
Output
Formatted date-time: 2024-06-01 15:30:00
Parsed LocalDateTime: 2024-06-01T15:30:00
Common Pitfalls
Common mistakes when using DateTimeFormatter include:
- Using a pattern that does not match the input string when parsing, causing exceptions.
- Confusing uppercase and lowercase letters in patterns (e.g.,
MMfor month vsmmfor minutes). - Not handling exceptions like
DateTimeParseExceptionwhen parsing invalid strings.
java
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; public class FormatterPitfall { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String wrongDateString = "2024-06-01 15:30"; // Missing seconds try { // This will throw an exception because pattern expects seconds LocalDateTime.parse(wrongDateString, formatter); } catch (DateTimeParseException e) { System.out.println("Parsing failed: " + e.getMessage()); } // Correct way: match pattern exactly String correctDateString = "2024-06-01 15:30:00"; LocalDateTime dateTime = LocalDateTime.parse(correctDateString, formatter); System.out.println("Parsed correctly: " + dateTime); } }
Output
Parsing failed: Text '2024-06-01 15:30' could not be parsed at index 16
Parsed correctly: 2024-06-01T15:30:00
Quick Reference
| Pattern Symbol | Meaning | Example |
|---|---|---|
| yyyy | Year (4 digits) | 2024 |
| MM | Month (2 digits) | 06 |
| dd | Day of month (2 digits) | 01 |
| HH | Hour (24-hour, 2 digits) | 15 |
| mm | Minute (2 digits) | 30 |
| ss | Second (2 digits) | 00 |
| a | AM/PM marker | PM |
Key Takeaways
Use DateTimeFormatter.ofPattern() with a pattern string to format or parse dates and times.
Ensure the pattern exactly matches the date/time string format when parsing to avoid errors.
Remember uppercase and lowercase letters in patterns have different meanings (e.g., MM vs mm).
Handle DateTimeParseException when parsing strings to catch format mismatches.
DateTimeFormatter works with LocalDate, LocalTime, and LocalDateTime classes for flexible date-time handling.