Practical Examples
Age Calculation
public int calculateAge(LocalDate birthDate) {
LocalDate currentDate = LocalDate.now();
return Period.between(birthDate, currentDate).getYears();
}
Membership Expiration Check
public boolean isMembershipActive(LocalDate startDate, int validMonths) {
LocalDate expirationDate = startDate.plusMonths(validMonths);
return LocalDate.now().isBefore(expirationDate);
}
Event Scheduling
Recurring Event Calculation
public List<LocalDate> generateEventDates(
LocalDate startDate,
int numberOfOccurrences,
int intervalDays
) {
List<LocalDate> eventDates = new ArrayList<>();
LocalDate currentDate = startDate;
for (int i = 0; i < numberOfOccurrences; i++) {
eventDates.add(currentDate);
currentDate = currentDate.plusDays(intervalDays);
}
return eventDates;
}
Business Day Calculations
graph TD
A[Business Day Calculation] --> B[Exclude Weekends]
A --> C[Skip Public Holidays]
A --> D[Add/Subtract Working Days]
Working Day Finder
public LocalDate findNextWorkingDay(LocalDate date) {
LocalDate nextDay = date;
while (isWeekend(nextDay)) {
nextDay = nextDay.plusDays(1);
}
return nextDay;
}
private boolean isWeekend(LocalDate date) {
DayOfWeek day = date.getDayOfWeek();
return day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY;
}
Date Range Filtering
Example: Filter Dates in a Specific Range
public List<LocalDate> filterDateRange(
List<LocalDate> dates,
LocalDate startDate,
LocalDate endDate
) {
return dates.stream()
.filter(date -> !date.isBefore(startDate) && !date.isAfter(endDate))
.collect(Collectors.toList());
}
Seasonal Analysis
Season |
Start Month |
End Month |
Spring |
March |
May |
Summer |
June |
August |
Autumn |
September |
November |
Winter |
December |
February |
public String determineSeason(LocalDate date) {
int month = date.getMonthValue();
switch (month) {
case 3: case 4: case 5: return "Spring";
case 6: case 7: case 8: return "Summer";
case 9: case 10: case 11: return "Autumn";
case 12: case 1: case 2: return "Winter";
default: return "Invalid Month";
}
}
LabEx Practical Approach
At LabEx, we recommend practicing these examples to gain proficiency in LocalDate
manipulation, ensuring robust date handling in real-world applications.
Best Practices
- Use immutable methods
- Handle edge cases
- Consider time zones when necessary
- Validate input dates
- Use stream operations for complex filtering
- Minimize date conversions
- Use built-in methods
- Cache frequently used date calculations
- Avoid unnecessary object creation