Practical Examples
Real-World Time Handling Scenarios
Event Management System
import java.time.*;
import java.util.List;
import java.util.ArrayList;
public class EventScheduler {
private List<Event> events = new ArrayList<>();
public void scheduleEvent(String name, LocalDateTime start, Duration duration) {
Event event = new Event(name, start, duration);
events.add(event);
}
public List<Event> getUpcomingEvents() {
LocalDateTime now = LocalDateTime.now();
return events.stream()
.filter(event -> event.getStartTime().isAfter(now))
.toList();
}
static class Event {
private String name;
private LocalDateTime startTime;
private Duration duration;
public Event(String name, LocalDateTime startTime, Duration duration) {
this.name = name;
this.startTime = startTime;
this.duration = duration;
}
public LocalDateTime getStartTime() {
return startTime;
}
}
}
Time-Based Calculation Patterns
Billing and Subscription Management
import java.time.*;
import java.math.BigDecimal;
public class SubscriptionCalculator {
public BigDecimal calculateProRatedCharge(
LocalDate subscriptionStart,
LocalDate billingDate,
BigDecimal monthlyRate
) {
Period activePeriod = Period.between(subscriptionStart, billingDate);
// Calculate pro-rated charge
double proRatedFactor = activePeriod.getDays() /
subscriptionStart.lengthOfMonth();
return monthlyRate.multiply(BigDecimal.valueOf(proRatedFactor));
}
}
Time Zone Conversion Utility
import java.time.*;
import java.time.format.DateTimeFormatter;
public class TimeZoneConverter {
public static ZonedDateTime convertTimeZone(
LocalDateTime sourceTime,
ZoneId sourceZone,
ZoneId targetZone
) {
ZonedDateTime sourceZonedTime = sourceTime.atZone(sourceZone);
return sourceZonedTime.withZoneSameInstant(targetZone);
}
public static void main(String[] args) {
LocalDateTime meeting = LocalDateTime.of(2023, 6, 15, 10, 0);
ZoneId newYork = ZoneId.of("America/New_York");
ZoneId tokyo = ZoneId.of("Asia/Tokyo");
ZonedDateTime convertedTime = convertTimeZone(
meeting, newYork, tokyo
);
System.out.println("Original Time: " + meeting + " " + newYork);
System.out.println("Converted Time: " + convertedTime);
}
}
Time Comparison and Validation
Booking System Example
import java.time.*;
import java.util.List;
import java.util.ArrayList;
public class BookingValidator {
private List<Booking> existingBookings = new ArrayList<>();
public boolean isTimeSlotAvailable(LocalDateTime proposedStart, Duration duration) {
LocalDateTime proposedEnd = proposedStart.plus(duration);
return existingBookings.stream().noneMatch(booking ->
isOverlapping(booking, proposedStart, proposedEnd)
);
}
private boolean isOverlapping(Booking existing, LocalDateTime newStart, LocalDateTime newEnd) {
return !(newEnd.isBefore(existing.getStartTime()) ||
newStart.isAfter(existing.getEndTime()));
}
static class Booking {
private LocalDateTime startTime;
private LocalDateTime endTime;
public Booking(LocalDateTime startTime, Duration duration) {
this.startTime = startTime;
this.endTime = startTime.plus(duration);
}
public LocalDateTime getStartTime() {
return startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
}
}
Time Complexity Analysis
graph TD
A[Time Operation] --> B{Complexity Type}
B --> |O(1)| C[Instant Creation]
B --> |O(1)| D[Time Zone Conversion]
B --> |O(n)| E[Large List Time Calculations]
B --> |O(log n)| F[Time-based Searching]
Practical Time Handling Patterns
Pattern |
Use Case |
Key Technique |
Immutable Preservation |
Concurrent Systems |
Create new instances |
Zone-Aware Calculations |
Global Applications |
Use ZonedDateTime |
Precise Duration Tracking |
Billing Systems |
Use Duration class |
Best Practices
- Always use Java Time API classes
- Prefer immutable time objects
- Handle time zones explicitly
- Use appropriate precision
- Validate time inputs
Learning with LabEx
At LabEx, we recommend practicing these patterns through hands-on coding exercises. Understanding practical time manipulation is crucial for robust software development.