Manipulating LocalDate Objects
Once you have created a LocalDate
object, you can perform various operations to manipulate the date. Here are some of the common date manipulation methods:
Adding and Subtracting Dates
You can add or subtract days, weeks, months, or years to a LocalDate
object using the following methods:
LocalDate date = LocalDate.of(2023, 4, 18);
// Adding 5 days
LocalDate newDate = date.plusDays(5); // 2023-04-23
// Subtracting 2 weeks
LocalDate previousDate = date.minusWeeks(2); // 2023-04-04
You can extract individual components of a LocalDate
object, such as the year, month, and day, using the following methods:
LocalDate date = LocalDate.of(2023, 4, 18);
int year = date.getYear(); // 2023
int month = date.getMonthValue(); // 4
int day = date.getDayOfMonth(); // 18
Comparing Dates
You can compare two LocalDate
objects using the following methods:
LocalDate date1 = LocalDate.of(2023, 4, 18);
LocalDate date2 = LocalDate.of(2023, 5, 1);
boolean isAfter = date2.isAfter(date1); // true
boolean isBefore = date1.isBefore(date2); // true
int daysBetween = (int) ChronoUnit.DAYS.between(date1, date2); // 13
You can format a LocalDate
object using a DateTimeFormatter
and parse a date string into a LocalDate
object:
LocalDate date = LocalDate.of(2023, 4, 18);
// Formatting a LocalDate object
String formattedDate = date.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); // "18/04/2023"
// Parsing a date string
LocalDate parsedDate = LocalDate.parse("18/04/2023", DateTimeFormatter.ofPattern("dd/MM/yyyy"));
By understanding these date manipulation methods, you can effectively work with LocalDate
objects to perform a wide range of date-related tasks in your Java applications.