Date and Time API
Overview of Java Time API
The Java Time API, introduced in Java 8, provides a comprehensive and modern approach to date and time manipulation.
Core Time Classes
graph TD
A[Java Time API] --> B[LocalDate]
A --> C[LocalTime]
A --> D[LocalDateTime]
A --> E[ZonedDateTime]
A --> F[Instant]
Creating Date and Time Objects
LocalDate Operations
// Creating dates
LocalDate today = LocalDate.now();
LocalDate specificDate = LocalDate.of(2023, 12, 31);
// Date manipulations
LocalDate futureDate = today.plusDays(30);
LocalDate pastDate = today.minusMonths(2);
LocalTime Operations
// Creating times
LocalTime currentTime = LocalTime.now();
LocalTime specificTime = LocalTime.of(14, 30, 0);
// Time manipulations
LocalTime laterTime = currentTime.plusHours(2);
LocalTime earlierTime = currentTime.minusMinutes(15);
Advanced Time Handling
DateTime Combinations
// Combining date and time
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime customDateTime = LocalDateTime.of(2023, 12, 31, 23, 59, 59);
Time Zone Management
// Working with time zones
ZoneId defaultZone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
Operation |
Method |
Example |
Parsing String to Date |
LocalDate.parse() |
LocalDate.parse("2023-12-31") |
Formatting Date |
DateTimeFormatter |
formatter.format(localDate) |
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = localDate.format(customFormatter);
Comparison and Calculation
Date Comparisons
LocalDate date1 = LocalDate.of(2023, 1, 1);
LocalDate date2 = LocalDate.of(2023, 12, 31);
boolean isBefore = date1.isBefore(date2);
boolean isAfter = date1.isAfter(date2);
Duration and Period
// Calculating time differences
LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2023, 12, 31);
Period period = Period.between(start, end);
long daysBetween = ChronoUnit.DAYS.between(start, end);
- Use immutable time classes
- Minimize type conversions
- Leverage built-in API methods
- Cache frequently used formatters
Error Handling
try {
LocalDate invalidDate = LocalDate.parse("invalid-date");
} catch (DateTimeParseException e) {
// Handle parsing errors
System.err.println("Invalid date format");
}
Best Practices
- Always use
java.time
package
- Prefer immutable time classes
- Use appropriate time zone handling
- Implement proper error checking
By mastering the Java Time API, developers can efficiently manage complex temporal operations with clean, readable code.