Advanced Time Handling
Timezone Management
graph TD
A[Timezone Handling] --> B[ZonedDateTime]
A --> C[Instant]
A --> D[TimeZone Conversion]
Working with ZonedDateTime
ZonedDateTime currentZonedTime = ZonedDateTime.now();
ZonedDateTime specificZonedTime = ZonedDateTime.of(
LocalDateTime.of(2023, 6, 15, 10, 30),
ZoneId.of("America/New_York")
);
Timezone Conversion
ZonedDateTime sourceTime = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
ZonedDateTime targetTime = sourceTime.withZoneSameInstant(ZoneId.of("Europe/London"));
Time Precision Handling
Precision Level |
Class |
Description |
Date |
LocalDate |
Year, Month, Day |
Time |
LocalTime |
Hour, Minute, Second |
DateTime |
LocalDateTime |
Combination of Date and Time |
Timestamp |
Instant |
Precise moment in UTC |
Timestamp Operations
Instant now = Instant.now();
Instant futureInstant = now.plus(Duration.ofHours(5));
Instant pastInstant = now.minus(Duration.ofDays(2));
Duration and Period Calculations
Duration (Time-based)
Duration duration = Duration.between(
LocalTime.of(10, 0),
LocalTime.of(15, 30)
);
long minutes = duration.toMinutes();
Period (Date-based)
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2024, 1, 1);
Period period = Period.between(startDate, endDate);
int years = period.getYears();
int months = period.getMonths();
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd HH:mm:ss z"
);
String formattedDateTime = ZonedDateTime.now().format(customFormatter);
graph TD
A[Performance Tips] --> B[Use Immutable Classes]
A --> C[Minimize Timezone Conversions]
A --> D[Prefer Instant for Comparisons]
Error Handling Strategies
try {
ZonedDateTime invalidTime = ZonedDateTime.parse("invalid-time-string");
} catch (DateTimeParseException e) {
// Handle parsing errors
System.err.println("Invalid time format");
}
Explore advanced time handling techniques with LabEx's comprehensive Java time tutorial!