Date formatting is crucial for presenting dates in a readable and consistent manner across different applications and locales.
Class |
Package |
Purpose |
DateTimeFormatter |
java.time.format |
Modern formatting for Java 8+ |
SimpleDateFormat |
java.text |
Legacy formatting for older Java versions |
graph TD
A[Date Formatting] --> B[Predefined Patterns]
A --> C[Custom Patterns]
A --> D[Localization]
B --> E[ISO_DATE]
B --> F[RFC_DATE]
C --> G[Custom Pattern Creation]
D --> H[Locale-Specific Formatting]
Predefined Patterns
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormattingDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDateTime dateTime = LocalDateTime.now();
// ISO Date Format
String isoDate = date.format(DateTimeFormatter.ISO_DATE);
System.out.println("ISO Date: " + isoDate);
// Basic Date Format
String basicFormat = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("Basic Format: " + basicFormat);
}
}
Complex Pattern Examples
public class CustomDateFormatting {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// Custom Formats
DateTimeFormatter[] formatters = {
DateTimeFormatter.ofPattern("MMMM dd, yyyy"),
DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"),
DateTimeFormatter.ofPattern("E, MMM dd yyyy")
};
for (DateTimeFormatter formatter : formatters) {
System.out.println(now.format(formatter));
}
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class LocalizedDateFormatting {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// Different Locale Formats
Locale[] locales = {
Locale.US,
Locale.FRANCE,
Locale.GERMANY
};
for (Locale locale : locales) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy", locale);
System.out.println(locale + ": " + now.format(formatter));
}
}
}
Pattern |
Meaning |
Example |
yyyy |
4-digit year |
2023 |
MM |
2-digit month |
07 |
dd |
2-digit day |
15 |
HH |
24-hour hour |
14 |
mm |
Minutes |
30 |
ss |
Seconds |
45 |
Best Practices
- Use
DateTimeFormatter
for new projects
- Avoid
SimpleDateFormat
in multi-threaded environments
- Consider locale and internationalization
- Use predefined formatters when possible
public class SafeDateFormatting {
public static String safelyFormatDate(LocalDateTime dateTime, String pattern) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return dateTime.format(formatter);
} catch (IllegalArgumentException e) {
System.err.println("Invalid date format pattern: " + pattern);
return null;
}
}
}
Conclusion
Mastering date formatting techniques allows developers to present dates consistently and professionally across different applications and cultural contexts.