Skip Top Navigation Bar

Using the LocalDate Class

import statements

To use the LocalDate class, you will need to include the import statement:

import java.time.LocalDate;

Alternative to Constructors

There isn’t a constructor for the LocalDate class, so you aren’t able to create a LocalDate object by doing:

You will get an error that states that the constructor cannot be applied.

There are a couple ways to create a LocalDate object.

Scenario 1

Suppose you are writing a rewards app and want to keep track of when a user has joined the app. This allows you to give them a special reward once they have been a member for a year. There is a static method, called now that can be used to create a LocalDate object with today’s date. A static method is called using the class name instead of using an object.

Note that the date is listed as year-month-day.

Scenario 2

Perhaps this same rewards app wants to record the user’s birthday to give them a free cookie every year around their birthday. After obtaining the String representation of their birthday, which is April 19, 2006, entered as 2006-04-19, we can use the static method parse to create a LocalDate object for their birthday.

Scenario 3

Another way you could set the birthday would be to use the static method ofwith the birthday entered as int values. For example:

Other Methods in LocalDate

Now that you have a date, there are some helpful methods that you can use to work with the date.

LocalDate minusDays(long daysToSubtract) and LocalDate plusDays(long daysToAdd)

Maybe we want to allow the user to receive their reward in a 30-day range around their birthday, 15 days prior and 15 days after their birthday. To do this, we need to obtain these dates. There are two methods that can be used to accomplish this:

boolean isAfter(ChronoLocalDate other) and boolean isBefore (ChronoLocalDate other)

int getYear() and LocalDate withYear(int year)

We have a birthday every year. In this code segment, we obtained the current year from today by using the getYear() method and then updated birthday to have the current year in the birthday by using the withYear() method.

There are many more useful methods for LocalDate. To find more, please visit the []LocalDate API](https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/time/LocalDate.html).