Java LocalDate & LocalDateTime Methods - Descriptions & Examples
Java Built-in Methods - LocalDate & LocalDateTime (Descriptions & Examples)
1. now()
- Description: Gets the current date or datetime.
- Example:
LocalDate today = LocalDate.now();
LocalDateTime now = LocalDateTime.now();
2. of(int year, int month, int dayOfMonth)
- Description: Creates a date with the given year, month, and day.
- Example:
LocalDate date = LocalDate.of(2023, 4, 10);
3. parse(CharSequence text)
- Description: Parses a string to create a date/datetime.
- Example:
LocalDate date = LocalDate.parse("2023-04-10");
4. getYear(), getMonth(), getDayOfMonth(), getDayOfWeek()
- Description: Returns parts of the date.
- Example:
int year = date.getYear();
DayOfWeek day = date.getDayOfWeek();
5. plusDays(), plusMonths(), plusYears()
- Description: Adds a time amount to the date.
- Example:
LocalDate nextWeek = date.plusDays(7);
6. minusDays(), minusMonths(), minusYears()
- Description: Subtracts a time amount from the date.
- Example:
LocalDate lastWeek = date.minusDays(7);
7. isBefore(), isAfter(), isEqual()
- Description: Compares two dates.
- Example:
boolean result = date.isBefore(LocalDate.now());
8. withDayOfMonth(), withMonth(), withYear()
- Description: Sets specific date parts.
- Example:
LocalDate updated = date.withMonth(12);
9. toString()
- Description: Returns the ISO 8601 string representation.
- Example:
String str = date.toString(); // "2023-04-10"
10. format(DateTimeFormatter formatter)
- Description: Formats the date using a pattern.
- Example:
String formatted = date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
11. toLocalDate(), toLocalTime()
- Description: Converts LocalDateTime to date or time only.
- Example:
LocalDate ld = dateTime.toLocalDate();
LocalTime lt = dateTime.toLocalTime();