Practical Coding
Real-World Date Manipulation Scenarios
Project Deadline Calculator
public class ProjectDeadlineCalculator {
public static LocalDate calculateProjectDeadline(LocalDate startDate, int projectDuration) {
// Add project duration in months
return startDate.plusMonths(projectDuration);
}
public static void main(String[] args) {
LocalDate projectStart = LocalDate.now();
LocalDate deadline = calculateProjectDeadline(projectStart, 3);
System.out.println("Project Deadline: " + deadline);
}
}
Age Calculation Utility
public class AgeCalculator {
public static int calculateAge(LocalDate birthDate) {
LocalDate currentDate = LocalDate.now();
return Period.between(birthDate, currentDate).getYears();
}
public static void main(String[] args) {
LocalDate birthDate = LocalDate.of(1990, 5, 15);
int age = calculateAge(birthDate);
System.out.println("Current Age: " + age);
}
}
Date Range Validation
public class DateRangeValidator {
public static boolean isValidBookingPeriod(LocalDate checkIn, LocalDate checkOut) {
return !checkIn.isAfter(checkOut) &&
!checkIn.isBefore(LocalDate.now());
}
public static void main(String[] args) {
LocalDate checkIn = LocalDate.of(2023, 7, 20);
LocalDate checkOut = LocalDate.of(2023, 7, 25);
boolean isValid = isValidBookingPeriod(checkIn, checkOut);
System.out.println("Booking is valid: " + isValid);
}
}
Common Date Manipulation Patterns
Scenario |
Method |
Example |
Add Business Days |
Custom Method |
Skip weekends |
Find Next Working Day |
Conditional Logic |
Avoid holidays |
Calculate Billing Cycles |
Period Manipulation |
Monthly/Quarterly |
Holiday and Weekend Handling
graph TD
A[Date Handling] --> B[Skip Weekends]
A --> C[Avoid Holidays]
A --> D[Business Day Calculation]
Advanced Date Range Processing
public class DateRangeProcessor {
public static List<LocalDate> generateDateRange(
LocalDate start, LocalDate end) {
return start.datesUntil(end.plusDays(1))
.collect(Collectors.toList());
}
public static void main(String[] args) {
LocalDate start = LocalDate.of(2023, 7, 1);
LocalDate end = LocalDate.of(2023, 7, 10);
List<LocalDate> dateRange = generateDateRange(start, end);
dateRange.forEach(System.out::println);
}
}
Error Handling and Validation
public class DateValidationUtils {
public static void validateDate(LocalDate date) {
Objects.requireNonNull(date, "Date cannot be null");
if (date.isAfter(LocalDate.now().plusYears(100))) {
throw new IllegalArgumentException("Date is too far in the future");
}
}
}
LabEx Learning Tip
Practice these practical scenarios in LabEx's interactive Java coding environments to reinforce your understanding of LocalDate manipulations.