Practical Date Handling
Real-World Date Scenarios
Age Calculation
import java.time.LocalDate;
import java.time.Period;
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 + " years");
}
}
Date Range Validation
Checking Date Ranges
import java.time.LocalDate;
public class DateRangeValidator {
public static boolean isValidReservationDate(LocalDate startDate, LocalDate endDate) {
LocalDate now = LocalDate.now();
return !startDate.isBefore(now) &&
!endDate.isBefore(startDate) &&
!endDate.isAfter(now.plusYears(1));
}
public static void main(String[] args) {
LocalDate start = LocalDate.now().plusDays(10);
LocalDate end = LocalDate.now().plusMonths(2);
boolean isValid = isValidReservationDate(start, end);
System.out.println("Reservation Date Valid: " + isValid);
}
}
Handling Business Days
Business Day Calculations
import java.time.DayOfWeek;
import java.time.LocalDate;
public class BusinessDayCalculator {
public static LocalDate nextBusinessDay(LocalDate date) {
LocalDate nextDay = date;
while (true) {
nextDay = nextDay.plusDays(1);
if (!(nextDay.getDayOfWeek() == DayOfWeek.SATURDAY ||
nextDay.getDayOfWeek() == DayOfWeek.SUNDAY)) {
break;
}
}
return nextDay;
}
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate nextBusiness = nextBusinessDay(today);
System.out.println("Next Business Day: " + nextBusiness);
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormattingExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter[] formatters = {
DateTimeFormatter.ofPattern("yyyy-MM-dd"),
DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"),
DateTimeFormatter.ofPattern("MMMM d, yyyy")
};
for (DateTimeFormatter formatter : formatters) {
System.out.println(formatter.format(now));
}
}
}
Date Operation Patterns
graph TD
A[Practical Date Handling] --> B[Age Calculation]
A --> C[Date Range Validation]
A --> D[Business Day Calculation]
A --> E[Advanced Formatting]
Common Date Handling Patterns
Scenario |
Recommended Approach |
Key Methods |
Age Calculation |
Use Period |
Period.between() |
Date Validation |
Compare dates |
isBefore() , isAfter() |
Business Days |
Skip weekends |
getDayOfWeek() |
Formatting |
Use DateTimeFormatter |
ofPattern() |
- Prefer immutable date classes
- Use built-in methods for calculations
- Cache frequently used formatters
- Avoid unnecessary date conversions
Note: At LabEx, we recommend practicing these practical date handling techniques to become proficient in Java date management.