Sub topic 3
Working with Calendar Dates Using LocalDate
Many programs need dates without any clock time. A birthday, a holiday, a due date, and a hotel check-in day are all examples. In java.time, the type for these is LocalDate.
LocalDate is a class that holds a year, a month, and a day. It has no time of day and no time zone. "Local" means the date is read from a wall calendar: it is the same date for anyone who reads it, wherever they are.
This chapter covers how to create a LocalDate, read its parts, build new dates from it, and compare dates. It also covers the edge cases that catch beginners.
When to Use LocalDate
Use LocalDate when the answer to "what time?" does not matter. A good test: if you would write the value on a paper calendar with no hour next to it, it is a LocalDate.
| Requirement | Good fit for LocalDate? |
|---|---|
| A person's date of birth | Yes |
| The day an invoice is due | Yes |
| A public holiday | Yes |
| The moment a payment was received | No, use `Instant` (covered later) |
| A meeting at 9:00 in New York | No, use `ZonedDateTime` (covered later) |
Creating a LocalDate
You never write new LocalDate(...). Instead you call a static factory method, which is a static method that builds and returns an object for you.
The three most common ones are:
LocalDate.of(year, month, day)builds a date from numbers.LocalDate.parse(text)reads a date from text such as"2024-11-05".LocalDate.now()returns today's date from your computer's clock.
import java.time.LocalDate;
import java.time.Month;
public class CreateDates {
public static void main(String[] args) {
LocalDate a = LocalDate.of(2024, 11, 5);
LocalDate b = LocalDate.of(2024, Month.NOVEMBER, 5);
LocalDate c = LocalDate.parse("2024-11-05");
LocalDate today = LocalDate.now();
System.out.println(a); // 2024-11-05
System.out.println(b); // 2024-11-05
System.out.println(c); // 2024-11-05
System.out.println(a.equals(c)); // true
System.out.println(today); // depends on the day you run it
}
}Notice that months are numbered 1 to 12. November is 11. The old Calendar class counted months from 0, which caused many bugs. java.time fixed this. You can also pass a Month constant like Month.NOVEMBER, which makes the code easier to read.
The parse method expects the ISO format. ISO 8601 is an international standard that writes dates as year-month-day with dashes, like 2024-11-05. The month and day must have two digits, so "2024-11-5" throws a DateTimeParseException. A later chapter shows how to read other formats with DateTimeFormatter.
Invalid Dates Are Rejected
LocalDate checks every date you build. If the date does not exist, it throws a DateTimeException right away instead of quietly rolling into the next month.
import java.time.DateTimeException;
import java.time.LocalDate;
public class InvalidDates {
public static void main(String[] args) {
try {
LocalDate.of(2023, 2, 29);
} catch (DateTimeException e) {
System.out.println("Rejected: " + e.getMessage());
// Rejected: Invalid date 'February 29' as '2023' is not a leap year
}
try {
LocalDate.of(2024, 13, 1);
} catch (DateTimeException e) {
System.out.println("Rejected month 13");
}
}
}This strict checking helps you. A bad date shows up as an error where it was created, not as a wrong answer much later.
Reading the Parts of a Date
A getter is a method that returns one piece of an object's data. LocalDate has getters for every part of a date. It can also answer calendar questions, such as how long the month is.
import java.time.LocalDate;
public class ReadDates {
public static void main(String[] args) {
LocalDate d = LocalDate.of(2024, 2, 29);
System.out.println(d.getYear()); // 2024
System.out.println(d.getMonthValue()); // 2
System.out.println(d.getMonth()); // FEBRUARY
System.out.println(d.getDayOfMonth()); // 29
System.out.println(d.getDayOfYear()); // 60
System.out.println(d.getDayOfWeek()); // THURSDAY
System.out.println(d.lengthOfMonth()); // 29
System.out.println(d.lengthOfYear()); // 366
System.out.println(d.isLeapYear()); // true
}
}getMonthValue() returns a plain number. getMonth() and getDayOfWeek() return enum constants, which are fixed named values like FEBRUARY or THURSDAY. Those types get their own chapter later.
Building New Dates from Old Ones
As the previous chapter explained, a LocalDate never changes. Methods that look like changes give you back a new date, and you must keep that result in a variable.
There are two families of these methods:
plus...andminus...move forward or backward:plusDays,plusWeeks,plusMonths,plusYears, and the matchingminusmethods.with...sets one part to a fixed value:withDayOfMonth,withMonth,withYear,withDayOfYear.
Because each call returns a LocalDate, you can chain calls one after another:
import java.time.LocalDate;
import java.time.Month;
public class Dates {
public static void main(String[] args) {
LocalDate release = LocalDate.of(2014, Month.MARCH, 18);
LocalDate later = release.plusMonths(1).plusDays(10);
System.out.println(release); // 2014-03-18
System.out.println(later); // 2014-04-28
System.out.println(later.getDayOfWeek()); // MONDAY
}
}Edge Case: Month Ends and Leap Days
What is one month after January 31? February has no 31st. LocalDate handles this by clamping, which means it uses the last valid day of the target month instead of throwing an error or spilling into March.
import java.time.LocalDate;
public class MonthEnds {
public static void main(String[] args) {
System.out.println(LocalDate.of(2024, 1, 31).plusMonths(1)); // 2024-02-29
System.out.println(LocalDate.of(2023, 1, 31).plusMonths(1)); // 2023-02-28
System.out.println(LocalDate.of(2024, 2, 29).plusYears(1)); // 2025-02-28
System.out.println(LocalDate.of(2024, 2, 29).withYear(2023)); // 2023-02-28
System.out.println(LocalDate.of(2024, 3, 31).withMonth(4)); // 2024-04-30
}
}Note the difference from LocalDate.of. Building February 29 in a non-leap year throws an error, but adding a year to February 29 clamps to February 28. The arithmetic methods always return a valid date.
Comparing Dates
To find out which date comes first, use these methods:
isBefore(other)returnstrueif this date is earlier.isAfter(other)returnstrueif this date is later.isEqual(other)orequals(other)returnstruefor the same date.compareTo(other)returns a negative number, zero, or a positive number. Sorting uses it.
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CompareDates {
public static void main(String[] args) {
LocalDate due = LocalDate.of(2024, 11, 15);
LocalDate paid = LocalDate.of(2024, 11, 18);
System.out.println(paid.isAfter(due)); // true
System.out.println(paid.isBefore(due)); // false
System.out.println(due.isEqual(LocalDate.parse("2024-11-15"))); // true
List<LocalDate> dates = new ArrayList<>();
dates.add(paid);
dates.add(due);
dates.add(LocalDate.of(2024, 1, 1));
Collections.sort(dates);
System.out.println(dates); // [2024-01-01, 2024-11-15, 2024-11-18]
}
}Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `date.plusDays(1);` with no assignment | The result is thrown away | `date = date.plusDays(1);` |
| Using 0 for January | `LocalDate.of(2024, 0, 1)` throws an exception | Months run 1 to 12, or use `Month.JANUARY` |
| Parsing `"5/11/2024"` with `parse` | `DateTimeParseException` | Use ISO text or a `DateTimeFormatter` |
| Comparing with `==` | Often `false` for equal dates | Use `equals` or `isEqual` |
| Expecting `plusMonths` to reverse exactly | Month-end dates drift | Use adjusters for month ends |
Exercise
What does this code print, and why? LocalDate d = LocalDate.of(2024, 3, 31); d.plusMonths(1); System.out.println(d.plusMonths(1).getDayOfMonth() + " " + d);
Show answer
It prints "30 2024-03-31". The first plusMonths(1) result is discarded, so d stays 2024-03-31. The second call returns 2024-04-30, because April has only 30 days and the day is clamped, so getDayOfMonth() returns 30.
Exercise
Write one line of Java that returns the first day of the month that a given LocalDate d falls in, and a second line that checks whether d is in a leap year.
Show answer
LocalDate first = d.withDayOfMonth(1); returns the first day of the month. boolean leap = d.isLeapYear(); checks for a leap year.
Exercise
Which of these lines throws an exception: LocalDate.of(2025, 2, 29), LocalDate.of(2024, 2, 29).plusYears(1), or LocalDate.parse("2025-02-28")?
Show answer
Only LocalDate.of(2025, 2, 29) throws a DateTimeException, because 2025 is not a leap year. plusYears(1) clamps to 2025-02-28, and the parse call is valid ISO text.