Date Manipulation Techniques
Basic Date Manipulation Methods
Adding and Subtracting Time
// Adding days to a date
LocalDate futureDate = LocalDate.now().plusDays(10);
// Subtracting months
LocalDate pastDate = LocalDate.now().minusMonths(3);
// Adding hours to a datetime
LocalDateTime futureDateTime = LocalDateTime.now().plusHours(5);
Advanced Manipulation Techniques
Using Temporal Adjusters
// First day of next month
LocalDate firstDayNextMonth = LocalDate.now()
.with(TemporalAdjusters.firstDayOfNextMonth());
// Last day of current year
LocalDate lastDayOfYear = LocalDate.now()
.with(TemporalAdjusters.lastDayOfYear());
Date Comparison Methods
LocalDate date1 = LocalDate.of(2023, 6, 15);
LocalDate date2 = LocalDate.of(2023, 7, 20);
// Checking if a date is before another
boolean isBefore = date1.isBefore(date2);
// Checking if dates are equal
boolean isEqual = date1.isEqual(date2);
// Comparing dates
int comparisonResult = date1.compareTo(date2);
Calculation of Periods and Durations
graph TD
A[Time Calculation] --> B[Period]
A --> C[Duration]
B --> D[Date-based Calculations]
C --> E[Time-based Calculations]
Period Calculations
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 12, 31);
Period period = Period.between(startDate, endDate);
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
Duration Calculations
LocalTime start = LocalTime.of(10, 30);
LocalTime end = LocalTime.of(14, 45);
Duration duration = Duration.between(start, end);
long hours = duration.toHours();
long minutes = duration.toMinutesPart();
LocalDateTime now = LocalDateTime.now();
// Custom formatting
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);
Key Manipulation Methods
Method |
Description |
Example |
plus() |
Add time |
date.plusDays(5) |
minus() |
Subtract time |
date.minusMonths(2) |
with() |
Modify specific fields |
date.withYear(2024) |
format() |
Convert to string |
date.format(formatter) |
Time Zone Manipulations
// Converting between time zones
ZonedDateTime newYorkTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
ZonedDateTime tokyoTime = newYorkTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
LabEx Recommendation
LabEx suggests practicing these manipulation techniques to become proficient in Java Time API date handling.
Best Practices
- Use immutable date objects
- Prefer specific time classes
- Handle time zones carefully
- Use appropriate formatting methods