If you’re working with dates in Java, the DateTimeFormatter class is your ultimate tool for converting between human-readable date strings and machine-friendly LocalDateTime objects. In this comprehensive guide, we’ll explore practical Java DateTimeFormatter examples to master date formatting, parsing, and customization.
Table of Contents
Why DateTimeFormatter Matters in Java
Java introduced DateTimeFormatter in Java 8 as part of the modern Date/Time API to replace the legacy SimpleDateFormat. Key advantages include:
- Thread-safe design (no concurrency issues)
- Immutable formatters (safe to reuse)
- Built-in formats (ISO standards, localized styles)
- Flexible pattern-based formatting
Creating DateTimeFormatter Instances
1. Predefined Formatters
Use built-in formats like ISO dates:
DateTimeFormatter isoDate = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDate date = LocalDate.now();
System.out.println(date.format(isoDate)); // Output: 2020-08-15
2. Custom Pattern-Based Formatters
Define your own patterns using ofPattern():
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime now = LocalDateTime.now();
System.out.println(now.format(customFormatter)); // Output: 15/08/2020 14:30
3. Localized Formatters
Format dates for specific locales:
DateTimeFormatter germanFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.GERMAN);
System.out.println(LocalDate.now().format(germanFormatter)); // Output: 15. Aug. 2020
Common DateTimeFormatter Patterns
| Pattern | Description | Example Output |
|---|---|---|
yyyy | 4-digit year | 2020 |
MM | 2-digit month | 08 |
| MMM | 3-letter month | Jan, Feb |
| MMMM | Complete month | January, February |
dd | 2-digit day | 15 |
HH | 24-hour hour | 14 |
mm | Minutes | 30 |
ss | Seconds | 45 |
EEE | Abbreviated weekday | Tue |
Parsing Dates with DateTimeFormatter
Convert strings to date objects:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate parsedDate = LocalDate.parse("2020-08-15", formatter);
System.out.println(parsedDate.getDayOfWeek()); // Output: TUESDAY
Best Practices
- Reuse formatters to avoid recreating instances.
- Specify a
Localefor localized patterns (e.g., month names). - Handle exceptions like
DateTimeParseExceptionfor invalid inputs. - Use predefined formatters (e.g.,
ISO_LOCAL_DATE) when possible.
FAQ
How is DateTimeFormatter better than SimpleDateFormat?
Unlike SimpleDateFormat, it’s thread-safe, immutable, and integrates seamlessly with Java 8’s Date/Time API.
How to format time zones?
DateTimeFormatter tzFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm z")
.withZone(ZoneId.of("America/New_York"));
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt.format(tzFormatter)); // Output: 2020-08-15 10:30 EDT