Date Manipulation
Adding and Subtracting Dates
LocalDate provides powerful methods for date arithmetic, allowing easy manipulation of dates.
Adding Days, Weeks, Months, and Years
LocalDate date = LocalDate.of(2023, 6, 15);
// Adding days
LocalDate futureDate = date.plusDays(10); // 2023-06-25
LocalDate pastDate = date.minusDays(5); // 2023-06-10
// Adding weeks
LocalDate nextWeek = date.plusWeeks(2); // 2023-07-06
// Adding months
LocalDate nextMonth = date.plusMonths(3); // 2023-09-15
// Adding years
LocalDate nextYear = date.plusYears(1); // 2024-06-15
Date Comparison Methods
graph TD
A[Date Comparison] --> B[isBefore()]
A --> C[isAfter()]
A --> D[isEqual()]
Comparing Dates
LocalDate date1 = LocalDate.of(2023, 6, 15);
LocalDate date2 = LocalDate.of(2023, 7, 20);
boolean isBefore = date1.isBefore(date2); // true
boolean isAfter = date1.isAfter(date2); // false
boolean isEqual = date1.isEqual(date2); // false
Advanced Date Manipulation
Temporal Adjusters
Adjuster |
Description |
Example |
firstDayOfMonth() |
Returns first day of current month |
2023-06-01 |
lastDayOfMonth() |
Returns last day of current month |
2023-06-30 |
plusMonths() |
Add months to a date |
2023-09-15 |
withDayOfMonth() |
Set specific day of month |
2023-06-20 |
LocalDate date = LocalDate.of(2023, 6, 15);
// First day of month
LocalDate firstDay = date.withDayOfMonth(1); // 2023-06-01
// Last day of month
LocalDate lastDay = date.withDayOfMonth(date.lengthOfMonth()); // 2023-06-30
// Complex manipulation
LocalDate adjustedDate = date.plusMonths(2).withDayOfMonth(10); // 2023-08-10
Period Calculations
LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2023, 12, 31);
Period period = Period.between(start, end);
int months = period.getMonths(); // 11
int days = period.getDays(); // 30
Best Practices
- Use immutable methods for date manipulation
- Prefer built-in methods over manual calculations
- Consider time zones when working with international dates
Enhance your date manipulation skills with LabEx's practical Java programming tutorials!