Date formatting allows developers to convert date objects into human-readable string representations and vice versa. Java provides powerful tools for flexible date formatting.
The primary class for date formatting in modern Java is DateTimeFormatter, which offers comprehensive formatting capabilities.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// Standard Formatting Patterns
DateTimeFormatter standardFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate currentDate = LocalDate.now();
String formattedDate = currentDate.format(customFormatter);
| Pattern |
Description |
Example |
yyyy |
Four-digit year |
2023 |
MM |
Two-digit month |
06 |
dd |
Two-digit day |
15 |
HH |
Hour (24-hour) |
14 |
mm |
Minutes |
30 |
ss |
Seconds |
45 |
graph TD
A[Date Object] --> B[Choose Formatter]
B --> C{Predefined or Custom}
C --> |Predefined| D[ISO_LOCAL_DATE]
C --> |Custom| E[Custom Pattern]
D --> F[Formatted String]
E --> F
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter localizedFormatter = DateTimeFormatter
.ofPattern("MMMM dd, yyyy", Locale.ENGLISH);
String localizedDate = dateTime.format(localizedFormatter);
String dateString = "2023-06-15";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate parsedDate = LocalDate.parse(dateString, parser);
- Database date storage
- User interface display
- Log file timestamps
- Report generation
Best Practices
- Use
DateTimeFormatter for modern date handling
- Choose appropriate formatting patterns
- Consider locale and internationalization
- Handle parsing exceptions
Learning with LabEx
Explore advanced date formatting techniques in LabEx's interactive Java programming environments to master these skills practically.
DateTimeFormatter is immutable and thread-safe
- Reuse formatters when possible
- Avoid creating multiple formatter instances
Error Handling
try {
String invalidDate = "2023/06/15";
LocalDate parsed = LocalDate.parse(invalidDate,
DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} catch (DateTimeParseException e) {
System.out.println("Invalid date format");
}