Custom format patterns provide ultimate flexibility in representing dates, allowing precise control over how LocalDate
is displayed.
Pattern Symbol Reference
Symbol |
Meaning |
Example |
y |
Year |
2023 |
M |
Month |
06 or June |
d |
Day of month |
15 |
D |
Day of year |
166 |
E |
Day of week |
Thursday |
Basic Custom Pattern
LocalDate date = LocalDate.now();
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String formattedDate = date.format(customFormatter);
System.out.println(formattedDate); // 2023/06/15
graph TD
A[Custom Formatting] --> B[Numeric Representations]
A --> C[Text Representations]
A --> D[Complex Patterns]
Numeric and Text Combinations
LocalDate date = LocalDate.now();
// Numeric month with text day
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(date.format(formatter1)); // 15 Jun 2023
// Full text representation
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy");
System.out.println(date.format(formatter2)); // Thursday, June 15, 2023
LocalDate date = LocalDate.now();
DateTimeFormatter germanFormatter = DateTimeFormatter.ofPattern("dd. MMMM yyyy", Locale.GERMAN);
System.out.println(date.format(germanFormatter)); // 15. Juni 2023
Pattern Complexity Examples
Detailed Date Representation
LocalDate date = LocalDate.of(2023, 6, 15);
DateTimeFormatter complexFormatter = DateTimeFormatter.ofPattern("'Date:' yyyy/MM/dd 'Week:' w 'Day:' D");
System.out.println(date.format(complexFormatter));
// Date: 2023/06/15 Week: 24 Day: 166
Pattern |
Description |
Example Output |
dd/MM/yyyy |
Standard date |
15/06/2023 |
MMMM dd, yyyy |
Full month name |
June 15, 2023 |
EEE, MMM d |
Abbreviated day and month |
Thu, Jun 15 |
Error Handling
Handling Invalid Patterns
try {
DateTimeFormatter invalidFormatter = DateTimeFormatter.ofPattern("invalid pattern");
} catch (IllegalArgumentException e) {
System.err.println("Invalid pattern: " + e.getMessage());
}
Best Practices
- Be consistent with formatting
- Consider internationalization
- Use appropriate pattern symbols
- Test complex patterns thoroughly
LabEx Recommendation
Custom date formatting is a powerful feature fully supported in LabEx Java programming environments, enabling precise date representation across various application scenarios.