Advanced Date and Time Operations
While the basic date and time operations covered in the previous section are sufficient for many use cases, the java.time
package also provides more advanced features and functionality.
Period and Duration
The Period
and Duration
classes are used to represent a span of time. Period
is used for date-based calculations (years, months, days), while Duration
is used for time-based calculations (hours, minutes, seconds, nanoseconds).
// Example: Calculating the number of years between two dates
LocalDate today = LocalDate.now();
LocalDate birthDate = LocalDate.of(1990, 5, 15);
Period period = Period.between(birthDate, today);
System.out.println(period.getYears()); // Output: 33
Temporal Adjusters
Temporal adjusters are used to modify dates and times in more complex ways. The java.time.temporal.TemporalAdjusters
class provides a set of predefined adjusters, such as "next Monday", "last day of the month", and "first day of the next year".
// Example: Finding the next Friday the 13th
LocalDate today = LocalDate.now();
LocalDate nextFriday13th = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY))
.with(TemporalAdjusters.dayOfMonthRange(13, 13));
System.out.println(nextFriday13th); // Output: 2023-05-12
The java.time.format.DateTimeFormatter
class provides a flexible way to parse and format dates and times. You can use predefined formatters or create custom ones to suit your needs.
// Example: Parsing and formatting a date and time
String dateTimeString = "2023-04-15T14:30:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
String formattedDateTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(formattedDateTime); // Output: 2023-04-15 14:30:00
By mastering these advanced date and time operations, you can handle a wide range of date and time-related tasks in your Java applications.